github.com/fozzysec/SiaPrime@v0.0.0-20190612043147-66c8e8d11fe3/node/api/routes.go (about)

     1  package api
     2  
     3  import (
     4  	"net/http"
     5  	"strings"
     6  	"time"
     7  
     8  	"github.com/julienschmidt/httprouter"
     9  	"SiaPrime/build"
    10  )
    11  
    12  // buildHttpRoutes sets up and returns an * httprouter.Router.
    13  // it connected the Router to the given api using the required
    14  // parameters: requiredUserAgent and requiredPassword
    15  func (api *API) buildHTTPRoutes(requiredUserAgent string, requiredPassword string) {
    16  	router := httprouter.New()
    17  
    18  	router.NotFound = http.HandlerFunc(UnrecognizedCallHandler)
    19  	router.RedirectTrailingSlash = false
    20  
    21  	// Consensus API Calls
    22  	if api.cs != nil {
    23  		router.GET("/consensus", api.consensusHandler)
    24  		router.GET("/consensus/blocks", api.consensusBlocksHandler)
    25  		router.POST("/consensus/validate/transactionset", api.consensusValidateTransactionsetHandler)
    26  		router.GET("/consensus/blocks/:height", api.consensusBlocksHandlerSanasol)
    27  		router.GET("/consensus/future/:height", api.consensusFutureBlocksHandler)
    28  	}
    29  
    30  	// Explorer API Calls
    31  	if api.explorer != nil {
    32  		router.GET("/explorer", api.explorerHandler)
    33  		router.GET("/explorer/blocks/:height", api.explorerBlocksHandler)
    34  		router.GET("/explorer/hashes/:hash", api.explorerHashHandler)
    35  	}
    36  
    37  	// Gateway API Calls
    38  	if api.gateway != nil {
    39  		router.GET("/gateway", api.gatewayHandler)
    40  		router.POST("/gateway/connect/:netaddress", RequirePassword(api.gatewayConnectHandler, requiredPassword))
    41  		router.POST("/gateway/disconnect/:netaddress", RequirePassword(api.gatewayDisconnectHandler, requiredPassword))
    42  	}
    43  
    44  	// Host API Calls
    45  	if api.host != nil {
    46  		// Calls directly pertaining to the host.
    47  		router.GET("/host", api.hostHandlerGET)                                                   // Get the host status.
    48  		router.POST("/host", RequirePassword(api.hostHandlerPOST, requiredPassword))              // Change the settings of the host.
    49  		router.POST("/host/announce", RequirePassword(api.hostAnnounceHandler, requiredPassword)) // Announce the host to the network.
    50  		router.GET("/host/contracts", api.hostContractInfoHandler)                                // Get info about contracts.
    51  		router.GET("/host/estimatescore", api.hostEstimateScoreGET)
    52  
    53  		// Calls pertaining to the storage manager that the host uses.
    54  		router.GET("/host/storage", api.storageHandler)
    55  		router.POST("/host/storage/folders/add", RequirePassword(api.storageFoldersAddHandler, requiredPassword))
    56  		router.POST("/host/storage/folders/remove", RequirePassword(api.storageFoldersRemoveHandler, requiredPassword))
    57  		router.POST("/host/storage/folders/resize", RequirePassword(api.storageFoldersResizeHandler, requiredPassword))
    58  		router.POST("/host/storage/sectors/delete/:merkleroot", RequirePassword(api.storageSectorsDeleteHandler, requiredPassword))
    59  	}
    60  
    61  	// Miner API Calls
    62  	if api.miner != nil {
    63  		router.GET("/miner", api.minerHandler)
    64  		router.GET("/miner/header", RequirePassword(api.minerHeaderHandlerGET, requiredPassword))
    65  		router.POST("/miner/header", RequirePassword(api.minerHeaderHandlerPOST, requiredPassword))
    66  		router.GET("/miner/start", RequirePassword(api.minerStartHandler, requiredPassword))
    67  		router.GET("/miner/stop", RequirePassword(api.minerStopHandler, requiredPassword))
    68  	}
    69  
    70  	// Mining pool API Calls
    71  	if api.pool != nil {
    72  		router.GET("/pool", api.poolHandler)
    73  		// router.GET("/pool/clients", api.poolGetClientsInfo)
    74  		// router.GET("/pool/client", api.poolGetClientInfo)
    75  		router.POST("/pool/config", RequirePassword(api.poolConfigHandlerPOST, requiredPassword)) // Change the settings of the host.
    76  		router.GET("/pool/config", RequirePassword(api.poolConfigHandler, requiredPassword))
    77  		// router.GET("/pool/blocks", api.poolGetBlocksInfo)
    78  		// router.GET("/pool/block", api.poolGetBlockInfo)
    79  	}
    80  
    81  	// Renter API Calls
    82  	if api.renter != nil {
    83  		router.GET("/renter", api.renterHandlerGET)
    84  		router.POST("/renter", RequirePassword(api.renterHandlerPOST, requiredPassword))
    85  		router.POST("/renter/contract/cancel", RequirePassword(api.renterContractCancelHandler, requiredPassword))
    86  		router.GET("/renter/contracts", api.renterContractsHandler)
    87  		router.GET("/renter/downloads", api.renterDownloadsHandler)
    88  		router.POST("/renter/downloads/clear", RequirePassword(api.renterClearDownloadsHandler, requiredPassword))
    89  		router.GET("/renter/files", api.renterFilesHandler)
    90  		router.GET("/renter/file/*siapath", api.renterFileHandlerGET)
    91  		router.GET("/renter/prices", api.renterPricesHandler)
    92  
    93  		// TODO: re-enable these routes once the new .sia format has been
    94  		// standardized and implemented.
    95  		// router.POST("/renter/load", RequirePassword(api.renterLoadHandler, requiredPassword))
    96  		// router.POST("/renter/loadascii", RequirePassword(api.renterLoadAsciiHandler, requiredPassword))
    97  		// router.GET("/renter/share", RequirePassword(api.renterShareHandler, requiredPassword))
    98  		// router.GET("/renter/shareascii", RequirePassword(api.renterShareAsciiHandler, requiredPassword))
    99  
   100  		router.POST("/renter/delete/*siapath", RequirePassword(api.renterDeleteHandler, requiredPassword))
   101  		router.GET("/renter/download/*siapath", RequirePassword(api.renterDownloadHandler, requiredPassword))
   102  		router.GET("/renter/downloadasync/*siapath", RequirePassword(api.renterDownloadAsyncHandler, requiredPassword))
   103  		router.POST("/renter/rename/*siapath", RequirePassword(api.renterRenameHandler, requiredPassword))
   104  		router.GET("/renter/stream/*siapath", api.renterStreamHandler)
   105  		router.POST("/renter/upload/*siapath", RequirePassword(api.renterUploadHandler, requiredPassword))
   106  		router.POST("/renter/file/*siapath", RequirePassword(api.renterFileHandlerPOST, requiredPassword))
   107  
   108  		// HostDB endpoints.
   109  		router.GET("/hostdb", api.hostdbHandler)
   110  		router.GET("/hostdb/active", api.hostdbActiveHandler)
   111  		router.GET("/hostdb/all", api.hostdbAllHandler)
   112  		router.GET("/hostdb/hosts/:pubkey", api.hostdbHostsHandler)
   113  	}
   114  
   115  	if api.stratumminer != nil {
   116  		router.GET("/stratumminer", api.stratumminerHandler)
   117  		router.POST("/stratumminer/start", api.stratumminerStartHandler)
   118  		router.POST("/stratumminer/stop", api.stratumminerStopHandler)
   119  	}
   120  
   121  	// Transaction pool API Calls
   122  	if api.tpool != nil {
   123  		router.GET("/tpool/fee", api.tpoolFeeHandlerGET)
   124  		router.GET("/tpool/raw/:id", api.tpoolRawHandlerGET)
   125  		router.POST("/tpool/raw", api.tpoolRawHandlerPOST)
   126  		router.GET("/tpool/confirmed/:id", api.tpoolConfirmedGET)
   127  
   128  		// TODO: re-enable this route once the transaction pool API has been finalized
   129  		//router.GET("/transactionpool/transactions", api.transactionpoolTransactionsHandler)
   130  	}
   131  
   132  	// Wallet API Calls
   133  	if api.wallet != nil {
   134  		router.GET("/wallet", api.walletHandler)
   135  		router.POST("/wallet/033x", RequirePassword(api.wallet033xHandler, requiredPassword))
   136  		router.GET("/wallet/address", RequirePassword(api.walletAddressHandler, requiredPassword))
   137  		router.GET("/wallet/addresses", api.walletAddressesHandler)
   138  		router.GET("/wallet/backup", RequirePassword(api.walletBackupHandler, requiredPassword))
   139  		router.POST("/wallet/init", RequirePassword(api.walletInitHandler, requiredPassword))
   140  		router.POST("/wallet/init/seed", RequirePassword(api.walletInitSeedHandler, requiredPassword))
   141  		router.POST("/wallet/lock", RequirePassword(api.walletLockHandler, requiredPassword))
   142  		router.POST("/wallet/seed", RequirePassword(api.walletSeedHandler, requiredPassword))
   143  		router.GET("/wallet/seeds", RequirePassword(api.walletSeedsHandler, requiredPassword))
   144  		router.POST("/wallet/siacoins", RequirePassword(api.walletSiacoinsHandler, requiredPassword))
   145  		router.POST("/wallet/siafunds", RequirePassword(api.walletSiafundsHandler, requiredPassword))
   146  		router.POST("/wallet/siagkey", RequirePassword(api.walletSiagkeyHandler, requiredPassword))
   147  		router.POST("/wallet/sweep/seed", RequirePassword(api.walletSweepSeedHandler, requiredPassword))
   148  		router.GET("/wallet/transaction/:id", api.walletTransactionHandler)
   149  		router.GET("/wallet/transactions", api.walletTransactionsHandler)
   150  		router.GET("/wallet/transactions/:addr", api.walletTransactionsAddrHandler)
   151  		router.GET("/wallet/verify/address/:addr", api.walletVerifyAddressHandler)
   152  		router.POST("/wallet/unlock", RequirePassword(api.walletUnlockHandler, requiredPassword))
   153  		router.POST("/wallet/changepassword", RequirePassword(api.walletChangePasswordHandler, requiredPassword))
   154  		router.GET("/wallet/unlockconditions/:addr", RequirePassword(api.walletUnlockConditionsHandlerGET, requiredPassword))
   155  		router.POST("/wallet/unlockconditions", RequirePassword(api.walletUnlockConditionsHandlerPOST, requiredPassword))
   156  		router.GET("/wallet/unspent", RequirePassword(api.walletUnspentHandler, requiredPassword))
   157  		router.POST("/wallet/sign", RequirePassword(api.walletSignHandler, requiredPassword))
   158  		router.GET("/wallet/watch", RequirePassword(api.walletWatchHandlerGET, requiredPassword))
   159  		router.POST("/wallet/watch", RequirePassword(api.walletWatchHandlerPOST, requiredPassword))
   160  	}
   161  
   162  	// Apply UserAgent middleware and return the Router
   163  	api.router = cleanCloseHandler(RequireUserAgent(router, requiredUserAgent))
   164  	return
   165  }
   166  
   167  // cleanCloseHandler wraps the entire API, ensuring that underlying conns are
   168  // not leaked if the remote end closes the connection before the underlying
   169  // handler finishes.
   170  func cleanCloseHandler(next http.Handler) http.Handler {
   171  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   172  		// Close this file handle either when the function completes or when the
   173  		// connection is done.
   174  		done := make(chan struct{})
   175  		go func(w http.ResponseWriter, r *http.Request) {
   176  			defer close(done)
   177  			next.ServeHTTP(w, r)
   178  		}(w, r)
   179  		select {
   180  		case <-done:
   181  		}
   182  
   183  		// Sanity check - thread should not take more than an hour to return. This
   184  		// must be done in a goroutine, otherwise the server will not close the
   185  		// underlying socket for this API call.
   186  		timer := time.NewTimer(time.Minute * 60)
   187  		go func() {
   188  			select {
   189  			case <-done:
   190  				timer.Stop()
   191  			case <-timer.C:
   192  				build.Severe("api call is taking more than 60 minutes to return:", r.URL.Path)
   193  			}
   194  		}()
   195  	})
   196  }
   197  
   198  // RequireUserAgent is middleware that requires all requests to set a
   199  // UserAgent that contains the specified string.
   200  func RequireUserAgent(h http.Handler, ua string) http.Handler {
   201  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
   202  		if !strings.Contains(req.UserAgent(), ua) && !isUnrestricted(req) {
   203  			WriteError(w, Error{"Browser access disabled due to security vulnerability. Use Sia-UI or siac."}, http.StatusBadRequest)
   204  			return
   205  		}
   206  		h.ServeHTTP(w, req)
   207  	})
   208  }
   209  
   210  // RequirePassword is middleware that requires a request to authenticate with a
   211  // password using HTTP basic auth. Usernames are ignored. Empty passwords
   212  // indicate no authentication is required.
   213  func RequirePassword(h httprouter.Handle, password string) httprouter.Handle {
   214  	// An empty password is equivalent to no password.
   215  	if password == "" {
   216  		return h
   217  	}
   218  	return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
   219  		_, pass, ok := req.BasicAuth()
   220  		if !ok || pass != password {
   221  			w.Header().Set("WWW-Authenticate", "Basic realm=\"SiaAPI\"")
   222  			WriteError(w, Error{"API authentication failed."}, http.StatusUnauthorized)
   223  			return
   224  		}
   225  		h(w, req, ps)
   226  	}
   227  }
   228  
   229  // isUnrestricted checks if a request may bypass the useragent check.
   230  func isUnrestricted(req *http.Request) bool {
   231  	return strings.HasPrefix(req.URL.Path, "/renter/stream/")
   232  }