There is also rather easy solution using suffix automaton. Namely, for each state v you know how many substrings correspond to v and how many times each of them occurs in the string(number of paths from the start to v and from v to the end, respectively). Then you just multiply something and count some partial sums 
Also, you must take care of multiple final states in the automaton, but it’s all details.