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