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

1149 lines
33 KiB

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