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
8 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
11 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
9 years ago
11 years ago
11 years ago
9 years ago
9 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
10 years ago
10 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package setting
  6. import (
  7. "crypto/rand"
  8. "encoding/base64"
  9. "fmt"
  10. "io"
  11. "net/mail"
  12. "net/url"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "code.gitea.io/git"
  23. "code.gitea.io/gitea/modules/log"
  24. _ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
  25. "code.gitea.io/gitea/modules/user"
  26. "github.com/Unknwon/com"
  27. "github.com/dgrijalva/jwt-go"
  28. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  29. _ "github.com/go-macaron/cache/redis"
  30. "github.com/go-macaron/session"
  31. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  32. "github.com/go-xorm/core"
  33. ini "gopkg.in/ini.v1"
  34. "strk.kbt.io/projects/go/libravatar"
  35. )
  36. // Scheme describes protocol types
  37. type Scheme string
  38. // enumerates all the scheme types
  39. const (
  40. HTTP Scheme = "http"
  41. HTTPS Scheme = "https"
  42. FCGI Scheme = "fcgi"
  43. UnixSocket Scheme = "unix"
  44. )
  45. // LandingPage describes the default page
  46. type LandingPage string
  47. // enumerates all the landing page types
  48. const (
  49. LandingPageHome LandingPage = "/"
  50. LandingPageExplore LandingPage = "/explore"
  51. )
  52. // settings
  53. var (
  54. // AppVer settings
  55. AppVer string
  56. AppBuiltWith string
  57. AppName string
  58. AppURL string
  59. AppSubURL string
  60. AppSubURLDepth int // Number of slashes
  61. AppPath string
  62. AppDataPath string
  63. // Server settings
  64. Protocol Scheme
  65. Domain string
  66. HTTPAddr string
  67. HTTPPort string
  68. LocalURL string
  69. OfflineMode bool
  70. DisableRouterLog bool
  71. CertFile string
  72. KeyFile string
  73. StaticRootPath string
  74. EnableGzip bool
  75. LandingPageURL LandingPage
  76. UnixSocketPermission uint32
  77. EnablePprof bool
  78. SSH = struct {
  79. Disabled bool `ini:"DISABLE_SSH"`
  80. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  81. Domain string `ini:"SSH_DOMAIN"`
  82. Port int `ini:"SSH_PORT"`
  83. ListenHost string `ini:"SSH_LISTEN_HOST"`
  84. ListenPort int `ini:"SSH_LISTEN_PORT"`
  85. RootPath string `ini:"SSH_ROOT_PATH"`
  86. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  87. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  88. MinimumKeySizeCheck bool `ini:"-"`
  89. MinimumKeySizes map[string]int `ini:"-"`
  90. }{
  91. Disabled: false,
  92. StartBuiltinServer: false,
  93. Domain: "",
  94. Port: 22,
  95. KeygenPath: "ssh-keygen",
  96. }
  97. LFS struct {
  98. StartServer bool `ini:"LFS_START_SERVER"`
  99. ContentPath string `ini:"LFS_CONTENT_PATH"`
  100. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  101. JWTSecretBytes []byte `ini:"-"`
  102. }
  103. // Security settings
  104. InstallLock bool
  105. SecretKey string
  106. LogInRememberDays int
  107. CookieUserName string
  108. CookieRememberName string
  109. ReverseProxyAuthUser string
  110. MinPasswordLength int
  111. ImportLocalPaths bool
  112. // Database settings
  113. UseSQLite3 bool
  114. UseMySQL bool
  115. UseMSSQL bool
  116. UsePostgreSQL bool
  117. UseTiDB bool
  118. // Indexer settings
  119. Indexer struct {
  120. IssuePath string
  121. UpdateQueueLength int
  122. }
  123. // Webhook settings
  124. Webhook = struct {
  125. QueueLength int
  126. DeliverTimeout int
  127. SkipTLSVerify bool
  128. Types []string
  129. PagingNum int
  130. }{
  131. QueueLength: 1000,
  132. DeliverTimeout: 5,
  133. SkipTLSVerify: false,
  134. PagingNum: 10,
  135. }
  136. // Repository settings
  137. Repository = struct {
  138. AnsiCharset string
  139. ForcePrivate bool
  140. MaxCreationLimit int
  141. MirrorQueueLength int
  142. PullRequestQueueLength int
  143. PreferredLicenses []string
  144. DisableHTTPGit bool
  145. // Repository editor settings
  146. Editor struct {
  147. LineWrapExtensions []string
  148. PreviewableFileModes []string
  149. } `ini:"-"`
  150. // Repository upload settings
  151. Upload struct {
  152. Enabled bool
  153. TempPath string
  154. AllowedTypes []string `delim:"|"`
  155. FileMaxSize int64
  156. MaxFiles int
  157. } `ini:"-"`
  158. // Repository local settings
  159. Local struct {
  160. LocalCopyPath string
  161. } `ini:"-"`
  162. }{
  163. AnsiCharset: "",
  164. ForcePrivate: false,
  165. MaxCreationLimit: -1,
  166. MirrorQueueLength: 1000,
  167. PullRequestQueueLength: 1000,
  168. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  169. DisableHTTPGit: false,
  170. // Repository editor settings
  171. Editor: struct {
  172. LineWrapExtensions []string
  173. PreviewableFileModes []string
  174. }{
  175. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  176. PreviewableFileModes: []string{"markdown"},
  177. },
  178. // Repository upload settings
  179. Upload: struct {
  180. Enabled bool
  181. TempPath string
  182. AllowedTypes []string `delim:"|"`
  183. FileMaxSize int64
  184. MaxFiles int
  185. }{
  186. Enabled: true,
  187. TempPath: "data/tmp/uploads",
  188. AllowedTypes: []string{},
  189. FileMaxSize: 3,
  190. MaxFiles: 5,
  191. },
  192. // Repository local settings
  193. Local: struct {
  194. LocalCopyPath string
  195. }{
  196. LocalCopyPath: "tmp/local-repo",
  197. },
  198. }
  199. RepoRootPath string
  200. ScriptType = "bash"
  201. // UI settings
  202. UI = struct {
  203. ExplorePagingNum int
  204. IssuePagingNum int
  205. FeedMaxCommitNum int
  206. ThemeColorMetaTag string
  207. MaxDisplayFileSize int64
  208. ShowUserEmail bool
  209. Admin struct {
  210. UserPagingNum int
  211. RepoPagingNum int
  212. NoticePagingNum int
  213. OrgPagingNum int
  214. } `ini:"ui.admin"`
  215. User struct {
  216. RepoPagingNum int
  217. } `ini:"ui.user"`
  218. Meta struct {
  219. Author string
  220. Description string
  221. Keywords string
  222. } `ini:"ui.meta"`
  223. }{
  224. ExplorePagingNum: 20,
  225. IssuePagingNum: 10,
  226. FeedMaxCommitNum: 5,
  227. ThemeColorMetaTag: `#6cc644`,
  228. MaxDisplayFileSize: 8388608,
  229. Admin: struct {
  230. UserPagingNum int
  231. RepoPagingNum int
  232. NoticePagingNum int
  233. OrgPagingNum int
  234. }{
  235. UserPagingNum: 50,
  236. RepoPagingNum: 50,
  237. NoticePagingNum: 25,
  238. OrgPagingNum: 50,
  239. },
  240. User: struct {
  241. RepoPagingNum int
  242. }{
  243. RepoPagingNum: 15,
  244. },
  245. Meta: struct {
  246. Author string
  247. Description string
  248. Keywords string
  249. }{
  250. Author: "Gitea - Git with a cup of tea",
  251. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  252. Keywords: "go,git,self-hosted,gitea",
  253. },
  254. }
  255. // Markdown settings
  256. Markdown = struct {
  257. EnableHardLineBreak bool
  258. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  259. FileExtensions []string
  260. }{
  261. EnableHardLineBreak: false,
  262. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  263. }
  264. // Admin settings
  265. Admin struct {
  266. DisableRegularOrgCreation bool
  267. }
  268. // Picture settings
  269. AvatarUploadPath string
  270. GravatarSource string
  271. DisableGravatar bool
  272. EnableFederatedAvatar bool
  273. LibravatarService *libravatar.Libravatar
  274. // Log settings
  275. LogRootPath string
  276. LogModes []string
  277. LogConfigs []string
  278. // Attachment settings
  279. AttachmentPath string
  280. AttachmentAllowedTypes string
  281. AttachmentMaxSize int64
  282. AttachmentMaxFiles int
  283. AttachmentEnabled bool
  284. // Time settings
  285. TimeFormat string
  286. // Cache settings
  287. CacheAdapter string
  288. CacheInterval int
  289. CacheConn string
  290. // Session settings
  291. SessionConfig session.Options
  292. CSRFCookieName = "_csrf"
  293. // Cron tasks
  294. Cron = struct {
  295. UpdateMirror struct {
  296. Enabled bool
  297. RunAtStart bool
  298. Schedule string
  299. } `ini:"cron.update_mirrors"`
  300. RepoHealthCheck struct {
  301. Enabled bool
  302. RunAtStart bool
  303. Schedule string
  304. Timeout time.Duration
  305. Args []string `delim:" "`
  306. } `ini:"cron.repo_health_check"`
  307. CheckRepoStats struct {
  308. Enabled bool
  309. RunAtStart bool
  310. Schedule string
  311. } `ini:"cron.check_repo_stats"`
  312. ArchiveCleanup struct {
  313. Enabled bool
  314. RunAtStart bool
  315. Schedule string
  316. OlderThan time.Duration
  317. } `ini:"cron.archive_cleanup"`
  318. SyncExternalUsers struct {
  319. Enabled bool
  320. RunAtStart bool
  321. Schedule string
  322. UpdateExisting bool
  323. } `ini:"cron.sync_external_users"`
  324. }{
  325. UpdateMirror: struct {
  326. Enabled bool
  327. RunAtStart bool
  328. Schedule string
  329. }{
  330. Enabled: true,
  331. RunAtStart: false,
  332. Schedule: "@every 10m",
  333. },
  334. RepoHealthCheck: struct {
  335. Enabled bool
  336. RunAtStart bool
  337. Schedule string
  338. Timeout time.Duration
  339. Args []string `delim:" "`
  340. }{
  341. Enabled: true,
  342. RunAtStart: false,
  343. Schedule: "@every 24h",
  344. Timeout: 60 * time.Second,
  345. Args: []string{},
  346. },
  347. CheckRepoStats: struct {
  348. Enabled bool
  349. RunAtStart bool
  350. Schedule string
  351. }{
  352. Enabled: true,
  353. RunAtStart: true,
  354. Schedule: "@every 24h",
  355. },
  356. ArchiveCleanup: struct {
  357. Enabled bool
  358. RunAtStart bool
  359. Schedule string
  360. OlderThan time.Duration
  361. }{
  362. Enabled: true,
  363. RunAtStart: true,
  364. Schedule: "@every 24h",
  365. OlderThan: 24 * time.Hour,
  366. },
  367. SyncExternalUsers: struct {
  368. Enabled bool
  369. RunAtStart bool
  370. Schedule string
  371. UpdateExisting bool
  372. }{
  373. Enabled: true,
  374. RunAtStart: false,
  375. Schedule: "@every 24h",
  376. UpdateExisting: true,
  377. },
  378. }
  379. // Git settings
  380. Git = struct {
  381. Version string `ini:"-"`
  382. DisableDiffHighlight bool
  383. MaxGitDiffLines int
  384. MaxGitDiffLineCharacters int
  385. MaxGitDiffFiles int
  386. GCArgs []string `delim:" "`
  387. Timeout struct {
  388. Migrate int
  389. Mirror int
  390. Clone int
  391. Pull int
  392. GC int `ini:"GC"`
  393. } `ini:"git.timeout"`
  394. }{
  395. DisableDiffHighlight: false,
  396. MaxGitDiffLines: 1000,
  397. MaxGitDiffLineCharacters: 500,
  398. MaxGitDiffFiles: 100,
  399. GCArgs: []string{},
  400. Timeout: struct {
  401. Migrate int
  402. Mirror int
  403. Clone int
  404. Pull int
  405. GC int `ini:"GC"`
  406. }{
  407. Migrate: 600,
  408. Mirror: 300,
  409. Clone: 300,
  410. Pull: 300,
  411. GC: 60,
  412. },
  413. }
  414. // Mirror settings
  415. Mirror struct {
  416. DefaultInterval time.Duration
  417. MinInterval time.Duration
  418. }
  419. // API settings
  420. API = struct {
  421. MaxResponseItems int
  422. }{
  423. MaxResponseItems: 50,
  424. }
  425. // I18n settings
  426. Langs []string
  427. Names []string
  428. dateLangs map[string]string
  429. // Highlight settings are loaded in modules/template/highlight.go
  430. // Other settings
  431. ShowFooterBranding bool
  432. ShowFooterVersion bool
  433. ShowFooterTemplateLoadTime bool
  434. // Global setting objects
  435. Cfg *ini.File
  436. CustomPath string // Custom directory path
  437. CustomConf string
  438. CustomPID string
  439. ProdMode bool
  440. RunUser string
  441. IsWindows bool
  442. HasRobotsTxt bool
  443. InternalToken string // internal access token
  444. )
  445. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  446. func DateLang(lang string) string {
  447. name, ok := dateLangs[lang]
  448. if ok {
  449. return name
  450. }
  451. return "en"
  452. }
  453. // execPath returns the executable path.
  454. func execPath() (string, error) {
  455. file, err := exec.LookPath(os.Args[0])
  456. if err != nil {
  457. return "", err
  458. }
  459. return filepath.Abs(file)
  460. }
  461. func init() {
  462. IsWindows = runtime.GOOS == "windows"
  463. log.NewLogger(0, "console", `{"level": 0}`)
  464. var err error
  465. if AppPath, err = execPath(); err != nil {
  466. log.Fatal(4, "Failed to get app path: %v", err)
  467. }
  468. // Note: we don't use path.Dir here because it does not handle case
  469. // which path starts with two "/" in Windows: "//psf/Home/..."
  470. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  471. }
  472. // WorkDir returns absolute path of work directory.
  473. func WorkDir() (string, error) {
  474. wd := os.Getenv("GITEA_WORK_DIR")
  475. if len(wd) > 0 {
  476. return wd, nil
  477. }
  478. // Use GOGS_WORK_DIR if available, for backward compatibility
  479. // TODO: drop in 1.1.0 ?
  480. wd = os.Getenv("GOGS_WORK_DIR")
  481. if len(wd) > 0 {
  482. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  483. please consider changing to GITEA_WORK_DIR`)
  484. return wd, nil
  485. }
  486. i := strings.LastIndex(AppPath, "/")
  487. if i == -1 {
  488. return AppPath, nil
  489. }
  490. return AppPath[:i], nil
  491. }
  492. func forcePathSeparator(path string) {
  493. if strings.Contains(path, "\\") {
  494. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  495. }
  496. }
  497. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  498. // actual user that runs the app. The first return value is the actual user name.
  499. // This check is ignored under Windows since SSH remote login is not the main
  500. // method to login on Windows.
  501. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  502. if IsWindows {
  503. return "", true
  504. }
  505. currentUser := user.CurrentUsername()
  506. return currentUser, runUser == currentUser
  507. }
  508. func createPIDFile(pidPath string) {
  509. currentPid := os.Getpid()
  510. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  511. log.Fatal(4, "Failed to create PID folder: %v", err)
  512. }
  513. file, err := os.Create(pidPath)
  514. if err != nil {
  515. log.Fatal(4, "Failed to create PID file: %v", err)
  516. }
  517. defer file.Close()
  518. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  519. log.Fatal(4, "Failed to write PID information: %v", err)
  520. }
  521. }
  522. // NewContext initializes configuration context.
  523. // NOTE: do not print any log except error.
  524. func NewContext() {
  525. workDir, err := WorkDir()
  526. if err != nil {
  527. log.Fatal(4, "Failed to get work directory: %v", err)
  528. }
  529. Cfg = ini.Empty()
  530. CustomPath = os.Getenv("GITEA_CUSTOM")
  531. if len(CustomPath) == 0 {
  532. // For backward compatibility
  533. // TODO: drop in 1.1.0 ?
  534. CustomPath = os.Getenv("GOGS_CUSTOM")
  535. if len(CustomPath) == 0 {
  536. CustomPath = workDir + "/custom"
  537. } else {
  538. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  539. please consider changing to GITEA_CUSTOM`)
  540. }
  541. }
  542. if len(CustomPID) > 0 {
  543. createPIDFile(CustomPID)
  544. }
  545. if len(CustomConf) == 0 {
  546. CustomConf = CustomPath + "/conf/app.ini"
  547. }
  548. if com.IsFile(CustomConf) {
  549. if err = Cfg.Append(CustomConf); err != nil {
  550. log.Fatal(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  551. }
  552. } else {
  553. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  554. }
  555. Cfg.NameMapper = ini.AllCapsUnderscore
  556. homeDir, err := com.HomeDir()
  557. if err != nil {
  558. log.Fatal(4, "Failed to get home directory: %v", err)
  559. }
  560. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  561. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  562. forcePathSeparator(LogRootPath)
  563. sec := Cfg.Section("server")
  564. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  565. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  566. AppURL = strings.TrimRight(AppURL, "/") + "/"
  567. // Check if has app suburl.
  568. url, err := url.Parse(AppURL)
  569. if err != nil {
  570. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  571. }
  572. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  573. // This value is empty if site does not have sub-url.
  574. AppSubURL = strings.TrimSuffix(url.Path, "/")
  575. AppSubURLDepth = strings.Count(AppSubURL, "/")
  576. Protocol = HTTP
  577. if sec.Key("PROTOCOL").String() == "https" {
  578. Protocol = HTTPS
  579. CertFile = sec.Key("CERT_FILE").String()
  580. KeyFile = sec.Key("KEY_FILE").String()
  581. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  582. Protocol = FCGI
  583. } else if sec.Key("PROTOCOL").String() == "unix" {
  584. Protocol = UnixSocket
  585. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  586. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  587. if err != nil || UnixSocketPermissionParsed > 0777 {
  588. log.Fatal(4, "Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  589. }
  590. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  591. }
  592. Domain = sec.Key("DOMAIN").MustString("localhost")
  593. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  594. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  595. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  596. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  597. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  598. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  599. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  600. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  601. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  602. switch sec.Key("LANDING_PAGE").MustString("home") {
  603. case "explore":
  604. LandingPageURL = LandingPageExplore
  605. default:
  606. LandingPageURL = LandingPageHome
  607. }
  608. if len(SSH.Domain) == 0 {
  609. SSH.Domain = Domain
  610. }
  611. SSH.RootPath = path.Join(homeDir, ".ssh")
  612. SSH.KeyTestPath = os.TempDir()
  613. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  614. log.Fatal(4, "Failed to map SSH settings: %v", err)
  615. }
  616. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  617. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  618. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  619. // When disable SSH, start builtin server value is ignored.
  620. if SSH.Disabled {
  621. SSH.StartBuiltinServer = false
  622. }
  623. if !SSH.Disabled && !SSH.StartBuiltinServer {
  624. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  625. log.Fatal(4, "Failed to create '%s': %v", SSH.RootPath, err)
  626. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  627. log.Fatal(4, "Failed to create '%s': %v", SSH.KeyTestPath, err)
  628. }
  629. }
  630. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  631. SSH.MinimumKeySizes = map[string]int{}
  632. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  633. for _, key := range minimumKeySizes {
  634. if key.MustInt() != -1 {
  635. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  636. }
  637. }
  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. EnableHTMLAlternative 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. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  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. parsed, err := mail.ParseAddress(MailService.From)
  1161. if err != nil {
  1162. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  1163. }
  1164. MailService.FromEmail = parsed.Address
  1165. log.Info("Mail Service Enabled")
  1166. }
  1167. func newRegisterMailService() {
  1168. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  1169. return
  1170. } else if MailService == nil {
  1171. log.Warn("Register Mail Service: Mail Service is not enabled")
  1172. return
  1173. }
  1174. Service.RegisterEmailConfirm = true
  1175. log.Info("Register Mail Service Enabled")
  1176. }
  1177. func newNotifyMailService() {
  1178. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  1179. return
  1180. } else if MailService == nil {
  1181. log.Warn("Notify Mail Service: Mail Service is not enabled")
  1182. return
  1183. }
  1184. Service.EnableNotifyMail = true
  1185. log.Info("Notify Mail Service Enabled")
  1186. }
  1187. func newWebhookService() {
  1188. sec := Cfg.Section("webhook")
  1189. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  1190. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  1191. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  1192. Webhook.Types = []string{"gitea", "gogs", "slack"}
  1193. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  1194. }
  1195. // NewServices initializes the services
  1196. func NewServices() {
  1197. newService()
  1198. newLogService()
  1199. NewXORMLogService(false)
  1200. newCacheService()
  1201. newSessionService()
  1202. newMailService()
  1203. newRegisterMailService()
  1204. newNotifyMailService()
  1205. newWebhookService()
  1206. }