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 40 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
8 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
8 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
8 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
10 years ago
10 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
8 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
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
9 years ago
11 years ago
11 years ago
9 years ago
9 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 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
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
8 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
8 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
8 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
8 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
8 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
8 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
8 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
8 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
8 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
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 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
8 years ago
10 years ago
10 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
8 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
8 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
8 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
8 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 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
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 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
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
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "code.gitea.io/git"
  22. "code.gitea.io/gitea/modules/log"
  23. _ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
  24. "code.gitea.io/gitea/modules/user"
  25. "github.com/Unknwon/com"
  26. "github.com/dgrijalva/jwt-go"
  27. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  28. _ "github.com/go-macaron/cache/redis"
  29. "github.com/go-macaron/session"
  30. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  31. "github.com/go-xorm/core"
  32. ini "gopkg.in/ini.v1"
  33. "strk.kbt.io/projects/go/libravatar"
  34. )
  35. // Scheme describes protocol types
  36. type Scheme string
  37. // enumerates all the scheme types
  38. const (
  39. HTTP Scheme = "http"
  40. HTTPS Scheme = "https"
  41. FCGI Scheme = "fcgi"
  42. UnixSocket Scheme = "unix"
  43. )
  44. // LandingPage describes the default page
  45. type LandingPage string
  46. // enumerates all the landing page types
  47. const (
  48. LandingPageHome LandingPage = "/"
  49. LandingPageExplore LandingPage = "/explore"
  50. )
  51. // settings
  52. var (
  53. // AppVer settings
  54. AppVer string
  55. AppBuiltWith string
  56. AppName string
  57. AppURL string
  58. AppSubURL string
  59. AppSubURLDepth int // Number of slashes
  60. AppPath string
  61. AppDataPath string
  62. // Server settings
  63. Protocol Scheme
  64. Domain string
  65. HTTPAddr string
  66. HTTPPort string
  67. LocalURL string
  68. OfflineMode bool
  69. DisableRouterLog bool
  70. CertFile string
  71. KeyFile string
  72. StaticRootPath string
  73. EnableGzip bool
  74. LandingPageURL LandingPage
  75. UnixSocketPermission uint32
  76. EnablePprof bool
  77. SSH = struct {
  78. Disabled bool `ini:"DISABLE_SSH"`
  79. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  80. Domain string `ini:"SSH_DOMAIN"`
  81. Port int `ini:"SSH_PORT"`
  82. ListenHost string `ini:"SSH_LISTEN_HOST"`
  83. ListenPort int `ini:"SSH_LISTEN_PORT"`
  84. RootPath string `ini:"SSH_ROOT_PATH"`
  85. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  86. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  87. MinimumKeySizeCheck bool `ini:"-"`
  88. MinimumKeySizes map[string]int `ini:"-"`
  89. }{
  90. Disabled: false,
  91. StartBuiltinServer: false,
  92. Domain: "",
  93. Port: 22,
  94. KeygenPath: "ssh-keygen",
  95. }
  96. LFS struct {
  97. StartServer bool `ini:"LFS_START_SERVER"`
  98. ContentPath string `ini:"LFS_CONTENT_PATH"`
  99. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  100. JWTSecretBytes []byte `ini:"-"`
  101. }
  102. // Security settings
  103. InstallLock bool
  104. SecretKey string
  105. LogInRememberDays int
  106. CookieUserName string
  107. CookieRememberName string
  108. ReverseProxyAuthUser string
  109. MinPasswordLength int
  110. ImportLocalPaths bool
  111. // Database settings
  112. UseSQLite3 bool
  113. UseMySQL bool
  114. UseMSSQL bool
  115. UsePostgreSQL bool
  116. UseTiDB bool
  117. // Indexer settings
  118. Indexer struct {
  119. IssuePath string
  120. UpdateQueueLength int
  121. }
  122. // Webhook settings
  123. Webhook = struct {
  124. QueueLength int
  125. DeliverTimeout int
  126. SkipTLSVerify bool
  127. Types []string
  128. PagingNum int
  129. }{
  130. QueueLength: 1000,
  131. DeliverTimeout: 5,
  132. SkipTLSVerify: false,
  133. PagingNum: 10,
  134. }
  135. // Repository settings
  136. Repository = struct {
  137. AnsiCharset string
  138. ForcePrivate bool
  139. MaxCreationLimit int
  140. MirrorQueueLength int
  141. PullRequestQueueLength int
  142. PreferredLicenses []string
  143. DisableHTTPGit bool
  144. // Repository editor settings
  145. Editor struct {
  146. LineWrapExtensions []string
  147. PreviewableFileModes []string
  148. } `ini:"-"`
  149. // Repository upload settings
  150. Upload struct {
  151. Enabled bool
  152. TempPath string
  153. AllowedTypes []string `delim:"|"`
  154. FileMaxSize int64
  155. MaxFiles int
  156. } `ini:"-"`
  157. }{
  158. AnsiCharset: "",
  159. ForcePrivate: false,
  160. MaxCreationLimit: -1,
  161. MirrorQueueLength: 1000,
  162. PullRequestQueueLength: 1000,
  163. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  164. DisableHTTPGit: false,
  165. // Repository editor settings
  166. Editor: struct {
  167. LineWrapExtensions []string
  168. PreviewableFileModes []string
  169. }{
  170. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  171. PreviewableFileModes: []string{"markdown"},
  172. },
  173. // Repository upload settings
  174. Upload: struct {
  175. Enabled bool
  176. TempPath string
  177. AllowedTypes []string `delim:"|"`
  178. FileMaxSize int64
  179. MaxFiles int
  180. }{
  181. Enabled: true,
  182. TempPath: "data/tmp/uploads",
  183. AllowedTypes: []string{},
  184. FileMaxSize: 3,
  185. MaxFiles: 5,
  186. },
  187. }
  188. RepoRootPath string
  189. ScriptType = "bash"
  190. // UI settings
  191. UI = struct {
  192. ExplorePagingNum int
  193. IssuePagingNum int
  194. FeedMaxCommitNum int
  195. ThemeColorMetaTag string
  196. MaxDisplayFileSize int64
  197. ShowUserEmail bool
  198. Admin struct {
  199. UserPagingNum int
  200. RepoPagingNum int
  201. NoticePagingNum int
  202. OrgPagingNum int
  203. } `ini:"ui.admin"`
  204. User struct {
  205. RepoPagingNum int
  206. } `ini:"ui.user"`
  207. Meta struct {
  208. Author string
  209. Description string
  210. Keywords string
  211. } `ini:"ui.meta"`
  212. }{
  213. ExplorePagingNum: 20,
  214. IssuePagingNum: 10,
  215. FeedMaxCommitNum: 5,
  216. ThemeColorMetaTag: `#6cc644`,
  217. MaxDisplayFileSize: 8388608,
  218. Admin: struct {
  219. UserPagingNum int
  220. RepoPagingNum int
  221. NoticePagingNum int
  222. OrgPagingNum int
  223. }{
  224. UserPagingNum: 50,
  225. RepoPagingNum: 50,
  226. NoticePagingNum: 25,
  227. OrgPagingNum: 50,
  228. },
  229. User: struct {
  230. RepoPagingNum int
  231. }{
  232. RepoPagingNum: 15,
  233. },
  234. Meta: struct {
  235. Author string
  236. Description string
  237. Keywords string
  238. }{
  239. Author: "Gitea - Git with a cup of tea",
  240. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  241. Keywords: "go,git,self-hosted,gitea",
  242. },
  243. }
  244. // Markdown settings
  245. Markdown = struct {
  246. EnableHardLineBreak bool
  247. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  248. FileExtensions []string
  249. }{
  250. EnableHardLineBreak: false,
  251. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  252. }
  253. // Admin settings
  254. Admin struct {
  255. DisableRegularOrgCreation bool
  256. }
  257. // Picture settings
  258. AvatarUploadPath string
  259. GravatarSource string
  260. DisableGravatar bool
  261. EnableFederatedAvatar bool
  262. LibravatarService *libravatar.Libravatar
  263. // Log settings
  264. LogRootPath string
  265. LogModes []string
  266. LogConfigs []string
  267. // Attachment settings
  268. AttachmentPath string
  269. AttachmentAllowedTypes string
  270. AttachmentMaxSize int64
  271. AttachmentMaxFiles int
  272. AttachmentEnabled bool
  273. // Time settings
  274. TimeFormat string
  275. // Cache settings
  276. CacheAdapter string
  277. CacheInterval int
  278. CacheConn string
  279. // Session settings
  280. SessionConfig session.Options
  281. CSRFCookieName = "_csrf"
  282. // Cron tasks
  283. Cron = struct {
  284. UpdateMirror struct {
  285. Enabled bool
  286. RunAtStart bool
  287. Schedule string
  288. } `ini:"cron.update_mirrors"`
  289. RepoHealthCheck struct {
  290. Enabled bool
  291. RunAtStart bool
  292. Schedule string
  293. Timeout time.Duration
  294. Args []string `delim:" "`
  295. } `ini:"cron.repo_health_check"`
  296. CheckRepoStats struct {
  297. Enabled bool
  298. RunAtStart bool
  299. Schedule string
  300. } `ini:"cron.check_repo_stats"`
  301. ArchiveCleanup struct {
  302. Enabled bool
  303. RunAtStart bool
  304. Schedule string
  305. OlderThan time.Duration
  306. } `ini:"cron.archive_cleanup"`
  307. }{
  308. UpdateMirror: struct {
  309. Enabled bool
  310. RunAtStart bool
  311. Schedule string
  312. }{
  313. Enabled: true,
  314. RunAtStart: false,
  315. Schedule: "@every 10m",
  316. },
  317. RepoHealthCheck: struct {
  318. Enabled bool
  319. RunAtStart bool
  320. Schedule string
  321. Timeout time.Duration
  322. Args []string `delim:" "`
  323. }{
  324. Enabled: true,
  325. RunAtStart: false,
  326. Schedule: "@every 24h",
  327. Timeout: 60 * time.Second,
  328. Args: []string{},
  329. },
  330. CheckRepoStats: struct {
  331. Enabled bool
  332. RunAtStart bool
  333. Schedule string
  334. }{
  335. Enabled: true,
  336. RunAtStart: true,
  337. Schedule: "@every 24h",
  338. },
  339. ArchiveCleanup: struct {
  340. Enabled bool
  341. RunAtStart bool
  342. Schedule string
  343. OlderThan time.Duration
  344. }{
  345. Enabled: true,
  346. RunAtStart: true,
  347. Schedule: "@every 24h",
  348. OlderThan: 24 * time.Hour,
  349. },
  350. }
  351. // Git settings
  352. Git = struct {
  353. Version string `ini:"-"`
  354. DisableDiffHighlight bool
  355. MaxGitDiffLines int
  356. MaxGitDiffLineCharacters int
  357. MaxGitDiffFiles int
  358. GCArgs []string `delim:" "`
  359. Timeout struct {
  360. Migrate int
  361. Mirror int
  362. Clone int
  363. Pull int
  364. GC int `ini:"GC"`
  365. } `ini:"git.timeout"`
  366. }{
  367. DisableDiffHighlight: false,
  368. MaxGitDiffLines: 1000,
  369. MaxGitDiffLineCharacters: 500,
  370. MaxGitDiffFiles: 100,
  371. GCArgs: []string{},
  372. Timeout: struct {
  373. Migrate int
  374. Mirror int
  375. Clone int
  376. Pull int
  377. GC int `ini:"GC"`
  378. }{
  379. Migrate: 600,
  380. Mirror: 300,
  381. Clone: 300,
  382. Pull: 300,
  383. GC: 60,
  384. },
  385. }
  386. // Mirror settings
  387. Mirror struct {
  388. DefaultInterval time.Duration
  389. MinInterval time.Duration
  390. }
  391. // API settings
  392. API = struct {
  393. MaxResponseItems int
  394. }{
  395. MaxResponseItems: 50,
  396. }
  397. // I18n settings
  398. Langs []string
  399. Names []string
  400. dateLangs map[string]string
  401. // Highlight settings are loaded in modules/template/highlight.go
  402. // Other settings
  403. ShowFooterBranding bool
  404. ShowFooterVersion bool
  405. ShowFooterTemplateLoadTime bool
  406. // Global setting objects
  407. Cfg *ini.File
  408. CustomPath string // Custom directory path
  409. CustomConf string
  410. CustomPID string
  411. ProdMode bool
  412. RunUser string
  413. IsWindows bool
  414. HasRobotsTxt bool
  415. InternalToken string // internal access token
  416. )
  417. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  418. func DateLang(lang string) string {
  419. name, ok := dateLangs[lang]
  420. if ok {
  421. return name
  422. }
  423. return "en"
  424. }
  425. // execPath returns the executable path.
  426. func execPath() (string, error) {
  427. file, err := exec.LookPath(os.Args[0])
  428. if err != nil {
  429. return "", err
  430. }
  431. return filepath.Abs(file)
  432. }
  433. func init() {
  434. IsWindows = runtime.GOOS == "windows"
  435. log.NewLogger(0, "console", `{"level": 0}`)
  436. var err error
  437. if AppPath, err = execPath(); err != nil {
  438. log.Fatal(4, "Failed to get app path: %v", err)
  439. }
  440. // Note: we don't use path.Dir here because it does not handle case
  441. // which path starts with two "/" in Windows: "//psf/Home/..."
  442. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  443. }
  444. // WorkDir returns absolute path of work directory.
  445. func WorkDir() (string, error) {
  446. wd := os.Getenv("GITEA_WORK_DIR")
  447. if len(wd) > 0 {
  448. return wd, nil
  449. }
  450. // Use GOGS_WORK_DIR if available, for backward compatibility
  451. // TODO: drop in 1.1.0 ?
  452. wd = os.Getenv("GOGS_WORK_DIR")
  453. if len(wd) > 0 {
  454. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  455. please consider changing to GITEA_WORK_DIR`)
  456. return wd, nil
  457. }
  458. i := strings.LastIndex(AppPath, "/")
  459. if i == -1 {
  460. return AppPath, nil
  461. }
  462. return AppPath[:i], nil
  463. }
  464. func forcePathSeparator(path string) {
  465. if strings.Contains(path, "\\") {
  466. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  467. }
  468. }
  469. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  470. // actual user that runs the app. The first return value is the actual user name.
  471. // This check is ignored under Windows since SSH remote login is not the main
  472. // method to login on Windows.
  473. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  474. if IsWindows {
  475. return "", true
  476. }
  477. currentUser := user.CurrentUsername()
  478. return currentUser, runUser == currentUser
  479. }
  480. func createPIDFile(pidPath string) {
  481. currentPid := os.Getpid()
  482. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  483. log.Fatal(4, "Failed to create PID folder: %v", err)
  484. }
  485. file, err := os.Create(pidPath)
  486. if err != nil {
  487. log.Fatal(4, "Failed to create PID file: %v", err)
  488. }
  489. defer file.Close()
  490. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  491. log.Fatal(4, "Failed to write PID information: %v", err)
  492. }
  493. }
  494. // NewContext initializes configuration context.
  495. // NOTE: do not print any log except error.
  496. func NewContext() {
  497. workDir, err := WorkDir()
  498. if err != nil {
  499. log.Fatal(4, "Failed to get work directory: %v", err)
  500. }
  501. Cfg = ini.Empty()
  502. CustomPath = os.Getenv("GITEA_CUSTOM")
  503. if len(CustomPath) == 0 {
  504. // For backward compatibility
  505. // TODO: drop in 1.1.0 ?
  506. CustomPath = os.Getenv("GOGS_CUSTOM")
  507. if len(CustomPath) == 0 {
  508. CustomPath = workDir + "/custom"
  509. } else {
  510. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  511. please consider changing to GITEA_CUSTOM`)
  512. }
  513. }
  514. if len(CustomPID) > 0 {
  515. createPIDFile(CustomPID)
  516. }
  517. if len(CustomConf) == 0 {
  518. CustomConf = CustomPath + "/conf/app.ini"
  519. }
  520. if com.IsFile(CustomConf) {
  521. if err = Cfg.Append(CustomConf); err != nil {
  522. log.Fatal(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  523. }
  524. } else {
  525. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  526. }
  527. Cfg.NameMapper = ini.AllCapsUnderscore
  528. homeDir, err := com.HomeDir()
  529. if err != nil {
  530. log.Fatal(4, "Failed to get home directory: %v", err)
  531. }
  532. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  533. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  534. forcePathSeparator(LogRootPath)
  535. sec := Cfg.Section("server")
  536. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  537. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  538. AppURL = strings.TrimRight(AppURL, "/") + "/"
  539. // Check if has app suburl.
  540. url, err := url.Parse(AppURL)
  541. if err != nil {
  542. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  543. }
  544. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  545. // This value is empty if site does not have sub-url.
  546. AppSubURL = strings.TrimSuffix(url.Path, "/")
  547. AppSubURLDepth = strings.Count(AppSubURL, "/")
  548. Protocol = HTTP
  549. if sec.Key("PROTOCOL").String() == "https" {
  550. Protocol = HTTPS
  551. CertFile = sec.Key("CERT_FILE").String()
  552. KeyFile = sec.Key("KEY_FILE").String()
  553. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  554. Protocol = FCGI
  555. } else if sec.Key("PROTOCOL").String() == "unix" {
  556. Protocol = UnixSocket
  557. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  558. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  559. if err != nil || UnixSocketPermissionParsed > 0777 {
  560. log.Fatal(4, "Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  561. }
  562. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  563. }
  564. Domain = sec.Key("DOMAIN").MustString("localhost")
  565. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  566. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  567. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  568. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  569. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  570. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  571. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  572. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  573. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  574. switch sec.Key("LANDING_PAGE").MustString("home") {
  575. case "explore":
  576. LandingPageURL = LandingPageExplore
  577. default:
  578. LandingPageURL = LandingPageHome
  579. }
  580. if len(SSH.Domain) == 0 {
  581. SSH.Domain = Domain
  582. }
  583. SSH.RootPath = path.Join(homeDir, ".ssh")
  584. SSH.KeyTestPath = os.TempDir()
  585. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  586. log.Fatal(4, "Failed to map SSH settings: %v", err)
  587. }
  588. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  589. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  590. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  591. // When disable SSH, start builtin server value is ignored.
  592. if SSH.Disabled {
  593. SSH.StartBuiltinServer = false
  594. }
  595. if !SSH.Disabled && !SSH.StartBuiltinServer {
  596. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  597. log.Fatal(4, "Failed to create '%s': %v", SSH.RootPath, err)
  598. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  599. log.Fatal(4, "Failed to create '%s': %v", SSH.KeyTestPath, err)
  600. }
  601. }
  602. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  603. SSH.MinimumKeySizes = map[string]int{}
  604. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  605. for _, key := range minimumKeySizes {
  606. if key.MustInt() != -1 {
  607. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  608. }
  609. }
  610. if err = Cfg.Section("server").MapTo(&LFS); err != nil {
  611. log.Fatal(4, "Failed to map LFS settings: %v", err)
  612. }
  613. if LFS.StartServer {
  614. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  615. log.Fatal(4, "Failed to create '%s': %v", LFS.ContentPath, err)
  616. }
  617. LFS.JWTSecretBytes = make([]byte, 32)
  618. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  619. if err != nil || n != 32 {
  620. //Generate new secret and save to config
  621. _, err := io.ReadFull(rand.Reader, LFS.JWTSecretBytes)
  622. if err != nil {
  623. log.Fatal(4, "Error reading random bytes: %v", err)
  624. }
  625. LFS.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(LFS.JWTSecretBytes)
  626. // Save secret
  627. cfg := ini.Empty()
  628. if com.IsFile(CustomConf) {
  629. // Keeps custom settings if there is already something.
  630. if err := cfg.Append(CustomConf); err != nil {
  631. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  632. }
  633. }
  634. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  635. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  636. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  637. }
  638. if err := cfg.SaveTo(CustomConf); err != nil {
  639. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  640. return
  641. }
  642. }
  643. //Disable LFS client hooks if installed for the current OS user
  644. //Needs at least git v2.1.2
  645. binVersion, err := git.BinVersion()
  646. if err != nil {
  647. log.Fatal(4, "Error retrieving git version: %v", err)
  648. }
  649. splitVersion := strings.SplitN(binVersion, ".", 3)
  650. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  651. if err != nil {
  652. log.Fatal(4, "Error parsing git major version: %v", err)
  653. }
  654. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  655. if err != nil {
  656. log.Fatal(4, "Error parsing git minor version: %v", err)
  657. }
  658. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  659. if err != nil {
  660. log.Fatal(4, "Error parsing git revision version: %v", err)
  661. }
  662. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  663. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  664. LFS.StartServer = false
  665. log.Error(4, "LFS server support needs at least Git v2.1.2")
  666. } else {
  667. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  668. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  669. }
  670. }
  671. sec = Cfg.Section("security")
  672. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  673. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  674. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  675. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  676. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  677. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  678. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  679. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  680. InternalToken = sec.Key("INTERNAL_TOKEN").String()
  681. if len(InternalToken) == 0 {
  682. secretBytes := make([]byte, 32)
  683. _, err := io.ReadFull(rand.Reader, secretBytes)
  684. if err != nil {
  685. log.Fatal(4, "Error reading random bytes: %v", err)
  686. }
  687. secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
  688. now := time.Now()
  689. InternalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  690. "nbf": now.Unix(),
  691. }).SignedString([]byte(secretKey))
  692. if err != nil {
  693. log.Fatal(4, "Error generate internal token: %v", err)
  694. }
  695. // Save secret
  696. cfgSave := ini.Empty()
  697. if com.IsFile(CustomConf) {
  698. // Keeps custom settings if there is already something.
  699. if err := cfgSave.Append(CustomConf); err != nil {
  700. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  701. }
  702. }
  703. cfgSave.Section("security").Key("INTERNAL_TOKEN").SetValue(InternalToken)
  704. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  705. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  706. }
  707. if err := cfgSave.SaveTo(CustomConf); err != nil {
  708. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  709. }
  710. }
  711. sec = Cfg.Section("attachment")
  712. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  713. if !filepath.IsAbs(AttachmentPath) {
  714. AttachmentPath = path.Join(workDir, AttachmentPath)
  715. }
  716. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png,application/zip,application/gzip"), "|", ",", -1)
  717. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  718. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  719. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  720. TimeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("RFC1123")
  721. TimeFormat = map[string]string{
  722. "ANSIC": time.ANSIC,
  723. "UnixDate": time.UnixDate,
  724. "RubyDate": time.RubyDate,
  725. "RFC822": time.RFC822,
  726. "RFC822Z": time.RFC822Z,
  727. "RFC850": time.RFC850,
  728. "RFC1123": time.RFC1123,
  729. "RFC1123Z": time.RFC1123Z,
  730. "RFC3339": time.RFC3339,
  731. "RFC3339Nano": time.RFC3339Nano,
  732. "Kitchen": time.Kitchen,
  733. "Stamp": time.Stamp,
  734. "StampMilli": time.StampMilli,
  735. "StampMicro": time.StampMicro,
  736. "StampNano": time.StampNano,
  737. }[TimeFormatKey]
  738. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  739. if len(TimeFormat) == 0 {
  740. TimeFormat = TimeFormatKey
  741. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  742. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  743. log.Fatal(4, "Can't create time properly, please check your time format has 2006, 01, 02, 15, 04 and 05")
  744. }
  745. log.Trace("Custom TimeFormat: %s", TimeFormat)
  746. }
  747. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  748. // Does not check run user when the install lock is off.
  749. if InstallLock {
  750. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  751. if !match {
  752. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  753. }
  754. }
  755. // Determine and create root git repository path.
  756. sec = Cfg.Section("repository")
  757. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  758. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  759. forcePathSeparator(RepoRootPath)
  760. if !filepath.IsAbs(RepoRootPath) {
  761. RepoRootPath = path.Join(workDir, RepoRootPath)
  762. } else {
  763. RepoRootPath = path.Clean(RepoRootPath)
  764. }
  765. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  766. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  767. log.Fatal(4, "Failed to map Repository settings: %v", err)
  768. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  769. log.Fatal(4, "Failed to map Repository.Editor settings: %v", err)
  770. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  771. log.Fatal(4, "Failed to map Repository.Upload settings: %v", err)
  772. }
  773. if !filepath.IsAbs(Repository.Upload.TempPath) {
  774. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  775. }
  776. sec = Cfg.Section("picture")
  777. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  778. forcePathSeparator(AvatarUploadPath)
  779. if !filepath.IsAbs(AvatarUploadPath) {
  780. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  781. }
  782. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  783. case "duoshuo":
  784. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  785. case "gravatar":
  786. GravatarSource = "https://secure.gravatar.com/avatar/"
  787. case "libravatar":
  788. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  789. default:
  790. GravatarSource = source
  791. }
  792. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  793. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  794. if OfflineMode {
  795. DisableGravatar = true
  796. EnableFederatedAvatar = false
  797. }
  798. if DisableGravatar {
  799. EnableFederatedAvatar = false
  800. }
  801. if EnableFederatedAvatar {
  802. LibravatarService = libravatar.New()
  803. parts := strings.Split(GravatarSource, "/")
  804. if len(parts) >= 3 {
  805. if parts[0] == "https:" {
  806. LibravatarService.SetUseHTTPS(true)
  807. LibravatarService.SetSecureFallbackHost(parts[2])
  808. } else {
  809. LibravatarService.SetUseHTTPS(false)
  810. LibravatarService.SetFallbackHost(parts[2])
  811. }
  812. }
  813. }
  814. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  815. log.Fatal(4, "Failed to map UI settings: %v", err)
  816. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  817. log.Fatal(4, "Failed to map Markdown settings: %v", err)
  818. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  819. log.Fatal(4, "Fail to map Admin settings: %v", err)
  820. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  821. log.Fatal(4, "Failed to map Cron settings: %v", err)
  822. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  823. log.Fatal(4, "Failed to map Git settings: %v", err)
  824. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  825. log.Fatal(4, "Failed to map API settings: %v", err)
  826. }
  827. sec = Cfg.Section("mirror")
  828. Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)
  829. Mirror.DefaultInterval = sec.Key("DEFAULT_INTERVAL").MustDuration(8 * time.Hour)
  830. if Mirror.MinInterval.Minutes() < 1 {
  831. log.Warn("Mirror.MinInterval is too low")
  832. Mirror.MinInterval = 1 * time.Minute
  833. }
  834. if Mirror.DefaultInterval < Mirror.MinInterval {
  835. log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval")
  836. Mirror.DefaultInterval = time.Hour * 8
  837. }
  838. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  839. if len(Langs) == 0 {
  840. Langs = defaultLangs
  841. }
  842. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  843. if len(Names) == 0 {
  844. Names = defaultLangNames
  845. }
  846. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  847. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  848. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  849. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  850. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  851. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  852. }
  853. // Service settings
  854. var Service struct {
  855. ActiveCodeLives int
  856. ResetPwdCodeLives int
  857. RegisterEmailConfirm bool
  858. DisableRegistration bool
  859. ShowRegistrationButton bool
  860. RequireSignInView bool
  861. EnableNotifyMail bool
  862. EnableReverseProxyAuth bool
  863. EnableReverseProxyAutoRegister bool
  864. EnableCaptcha bool
  865. DefaultKeepEmailPrivate bool
  866. NoReplyAddress string
  867. // OpenID settings
  868. EnableOpenIDSignIn bool
  869. EnableOpenIDSignUp bool
  870. OpenIDWhitelist []*regexp.Regexp
  871. OpenIDBlacklist []*regexp.Regexp
  872. }
  873. func newService() {
  874. sec := Cfg.Section("service")
  875. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  876. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  877. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  878. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  879. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  880. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  881. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  882. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  883. Service.DefaultKeepEmailPrivate = sec.Key("DEFAULT_KEEP_EMAIL_PRIVATE").MustBool()
  884. Service.NoReplyAddress = sec.Key("NO_REPLY_ADDRESS").MustString("noreply.example.org")
  885. sec = Cfg.Section("openid")
  886. Service.EnableOpenIDSignIn = sec.Key("ENABLE_OPENID_SIGNIN").MustBool(false)
  887. Service.EnableOpenIDSignUp = sec.Key("ENABLE_OPENID_SIGNUP").MustBool(!Service.DisableRegistration && Service.EnableOpenIDSignIn)
  888. pats := sec.Key("WHITELISTED_URIS").Strings(" ")
  889. if len(pats) != 0 {
  890. Service.OpenIDWhitelist = make([]*regexp.Regexp, len(pats))
  891. for i, p := range pats {
  892. Service.OpenIDWhitelist[i] = regexp.MustCompilePOSIX(p)
  893. }
  894. }
  895. pats = sec.Key("BLACKLISTED_URIS").Strings(" ")
  896. if len(pats) != 0 {
  897. Service.OpenIDBlacklist = make([]*regexp.Regexp, len(pats))
  898. for i, p := range pats {
  899. Service.OpenIDBlacklist[i] = regexp.MustCompilePOSIX(p)
  900. }
  901. }
  902. }
  903. var logLevels = map[string]string{
  904. "Trace": "0",
  905. "Debug": "1",
  906. "Info": "2",
  907. "Warn": "3",
  908. "Error": "4",
  909. "Critical": "5",
  910. }
  911. func newLogService() {
  912. log.Info("Gitea v%s%s", AppVer, AppBuiltWith)
  913. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  914. LogConfigs = make([]string, len(LogModes))
  915. useConsole := false
  916. for i := 0; i < len(LogModes); i++ {
  917. LogModes[i] = strings.TrimSpace(LogModes[i])
  918. if LogModes[i] == "console" {
  919. useConsole = true
  920. }
  921. }
  922. if !useConsole {
  923. log.DelLogger("console")
  924. }
  925. for i, mode := range LogModes {
  926. sec, err := Cfg.GetSection("log." + mode)
  927. if err != nil {
  928. sec, _ = Cfg.NewSection("log." + mode)
  929. }
  930. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  931. // Log level.
  932. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  933. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  934. validLevels)
  935. level, ok := logLevels[levelName]
  936. if !ok {
  937. log.Fatal(4, "Unknown log level: %s", levelName)
  938. }
  939. // Generate log configuration.
  940. switch mode {
  941. case "console":
  942. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  943. case "file":
  944. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gitea.log"))
  945. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  946. panic(err.Error())
  947. }
  948. LogConfigs[i] = fmt.Sprintf(
  949. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  950. logPath,
  951. sec.Key("LOG_ROTATE").MustBool(true),
  952. sec.Key("MAX_LINES").MustInt(1000000),
  953. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  954. sec.Key("DAILY_ROTATE").MustBool(true),
  955. sec.Key("MAX_DAYS").MustInt(7))
  956. case "conn":
  957. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  958. sec.Key("RECONNECT_ON_MSG").MustBool(),
  959. sec.Key("RECONNECT").MustBool(),
  960. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  961. sec.Key("ADDR").MustString(":7020"))
  962. case "smtp":
  963. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  964. sec.Key("USER").MustString("example@example.com"),
  965. sec.Key("PASSWD").MustString("******"),
  966. sec.Key("HOST").MustString("127.0.0.1:25"),
  967. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  968. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  969. case "database":
  970. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  971. sec.Key("DRIVER").String(),
  972. sec.Key("CONN").String())
  973. }
  974. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  975. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  976. }
  977. }
  978. // NewXORMLogService initializes xorm logger service
  979. func NewXORMLogService(disableConsole bool) {
  980. logModes := strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  981. var logConfigs string
  982. for _, mode := range logModes {
  983. mode = strings.TrimSpace(mode)
  984. if disableConsole && mode == "console" {
  985. continue
  986. }
  987. sec, err := Cfg.GetSection("log." + mode)
  988. if err != nil {
  989. sec, _ = Cfg.NewSection("log." + mode)
  990. }
  991. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  992. // Log level.
  993. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  994. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  995. validLevels)
  996. level, ok := logLevels[levelName]
  997. if !ok {
  998. log.Fatal(4, "Unknown log level: %s", levelName)
  999. }
  1000. // Generate log configuration.
  1001. switch mode {
  1002. case "console":
  1003. logConfigs = fmt.Sprintf(`{"level":%s}`, level)
  1004. case "file":
  1005. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "xorm.log"))
  1006. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1007. panic(err.Error())
  1008. }
  1009. logPath = filepath.Join(filepath.Dir(logPath), "xorm.log")
  1010. logConfigs = fmt.Sprintf(
  1011. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1012. logPath,
  1013. sec.Key("LOG_ROTATE").MustBool(true),
  1014. sec.Key("MAX_LINES").MustInt(1000000),
  1015. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1016. sec.Key("DAILY_ROTATE").MustBool(true),
  1017. sec.Key("MAX_DAYS").MustInt(7))
  1018. case "conn":
  1019. logConfigs = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1020. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1021. sec.Key("RECONNECT").MustBool(),
  1022. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1023. sec.Key("ADDR").MustString(":7020"))
  1024. case "smtp":
  1025. logConfigs = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  1026. sec.Key("USER").MustString("example@example.com"),
  1027. sec.Key("PASSWD").MustString("******"),
  1028. sec.Key("HOST").MustString("127.0.0.1:25"),
  1029. sec.Key("RECEIVERS").MustString("[]"),
  1030. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1031. case "database":
  1032. logConfigs = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1033. sec.Key("DRIVER").String(),
  1034. sec.Key("CONN").String())
  1035. }
  1036. log.NewXORMLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, logConfigs)
  1037. if !disableConsole {
  1038. log.Info("XORM Log Mode: %s(%s)", strings.Title(mode), levelName)
  1039. }
  1040. var lvl core.LogLevel
  1041. switch levelName {
  1042. case "Trace", "Debug":
  1043. lvl = core.LOG_DEBUG
  1044. case "Info":
  1045. lvl = core.LOG_INFO
  1046. case "Warn":
  1047. lvl = core.LOG_WARNING
  1048. case "Error", "Critical":
  1049. lvl = core.LOG_ERR
  1050. }
  1051. log.XORMLogger.SetLevel(lvl)
  1052. }
  1053. if len(logConfigs) == 0 {
  1054. log.DiscardXORMLogger()
  1055. }
  1056. }
  1057. func newCacheService() {
  1058. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  1059. switch CacheAdapter {
  1060. case "memory":
  1061. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  1062. case "redis", "memcache":
  1063. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  1064. default:
  1065. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  1066. }
  1067. log.Info("Cache Service Enabled")
  1068. }
  1069. func newSessionService() {
  1070. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  1071. []string{"memory", "file", "redis", "mysql"})
  1072. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  1073. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  1074. SessionConfig.CookiePath = AppSubURL
  1075. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  1076. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  1077. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  1078. log.Info("Session Service Enabled")
  1079. }
  1080. // Mailer represents mail service.
  1081. type Mailer struct {
  1082. // Mailer
  1083. QueueLength int
  1084. Name string
  1085. From string
  1086. FromEmail string
  1087. EnableHTMLAlternative bool
  1088. // SMTP sender
  1089. Host string
  1090. User, Passwd string
  1091. DisableHelo bool
  1092. HeloHostname string
  1093. SkipVerify bool
  1094. UseCertificate bool
  1095. CertFile, KeyFile string
  1096. // Sendmail sender
  1097. UseSendmail bool
  1098. SendmailPath string
  1099. }
  1100. var (
  1101. // MailService the global mailer
  1102. MailService *Mailer
  1103. )
  1104. func newMailService() {
  1105. sec := Cfg.Section("mailer")
  1106. // Check mailer setting.
  1107. if !sec.Key("ENABLED").MustBool() {
  1108. return
  1109. }
  1110. MailService = &Mailer{
  1111. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  1112. Name: sec.Key("NAME").MustString(AppName),
  1113. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  1114. Host: sec.Key("HOST").String(),
  1115. User: sec.Key("USER").String(),
  1116. Passwd: sec.Key("PASSWD").String(),
  1117. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  1118. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  1119. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  1120. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  1121. CertFile: sec.Key("CERT_FILE").String(),
  1122. KeyFile: sec.Key("KEY_FILE").String(),
  1123. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  1124. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  1125. }
  1126. MailService.From = sec.Key("FROM").MustString(MailService.User)
  1127. parsed, err := mail.ParseAddress(MailService.From)
  1128. if err != nil {
  1129. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  1130. }
  1131. MailService.FromEmail = parsed.Address
  1132. log.Info("Mail Service Enabled")
  1133. }
  1134. func newRegisterMailService() {
  1135. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  1136. return
  1137. } else if MailService == nil {
  1138. log.Warn("Register Mail Service: Mail Service is not enabled")
  1139. return
  1140. }
  1141. Service.RegisterEmailConfirm = true
  1142. log.Info("Register Mail Service Enabled")
  1143. }
  1144. func newNotifyMailService() {
  1145. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  1146. return
  1147. } else if MailService == nil {
  1148. log.Warn("Notify Mail Service: Mail Service is not enabled")
  1149. return
  1150. }
  1151. Service.EnableNotifyMail = true
  1152. log.Info("Notify Mail Service Enabled")
  1153. }
  1154. func newWebhookService() {
  1155. sec := Cfg.Section("webhook")
  1156. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  1157. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  1158. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  1159. Webhook.Types = []string{"gogs", "slack"}
  1160. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  1161. }
  1162. // NewServices initializes the services
  1163. func NewServices() {
  1164. newService()
  1165. newLogService()
  1166. NewXORMLogService(false)
  1167. newCacheService()
  1168. newSessionService()
  1169. newMailService()
  1170. newRegisterMailService()
  1171. newNotifyMailService()
  1172. newWebhookService()
  1173. }