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

setting.go 40 kB

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