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 41 kB

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