title: samba mangled filename algorithm (hash2) to unix filename in python
body: <p>my task is very simple, I have a list of files with some of them mangled by samba that I have to process in a linux environment using some python scripts.
  I want to build a function that converts the samba hash2 mangled form into the original unix path.</p>
  <p>After reading the smb configuration of the server, mangled files are generated by using hash2 and 1 character prefix + magic char '~'.</p>
  <p>In samba docs : <a href="https://www.samba.org/samba/docs/current/man-html/smb.conf.5.html" rel="nofollow noreferrer">https://www.samba.org/samba/docs/current/man-html/smb.conf.5.html</a>
  there is no mention of how hash2 is computed, and I can't find any answer elsewhere.</p>
  <p>Moreover, is the full path used to compute the hash2 or only the last directory name?
  for example:</p>
  <pre><code>Z:/aaa/bbb/ccc/T3XBGA~5/3 - Two Shell - LabBaby™.mp3 //mangled form
  
  /aaa/bbb/ccc/Two Shell - SoulCity E.P./3 - Two Shell - LabBaby™.mp3 //original unix path
  </code></pre>
  <p>as you see mangling occurs because only one file of this folder is using a unicode character, but what part of the unix path is used to compute this hash? and how to make the reverse conversion ?</p>
  <p>Thanks in advance</p>
  <p><strong>EDIT :</strong>  While reading samba source code, I realized that I was wrong saying dir name was mangled because of the unicode ™ character, in this case, it was mangled because directory name has 2 dots and end with '.'</p>
  <pre class="lang-c prettyprint-override"><code>    // mangle_hash2.c
      if (dot_p) {
          /* if the extension contains any illegal characters or
             is too long or zero length then we treat it as part
             of the prefix */
          for (i=0; i&lt;4 &amp;&amp; dot_p[i+1]; i++) {
              if (! FLAG_CHECK(dot_p[i+1], FLAG_ASCII)) {
                  dot_p = NULL;
                  break;
              }
          }
          if (i == 0 || i == 4) {
              dot_p = NULL;
          }
  </code></pre>
  <p><a href="https://github.com/samba-team/samba/blob/24fb40a812184fa57458ae9f0f4ffbced1dee09a/source3/smbd/mangle_hash2.c#L707" rel="nofollow noreferrer">https://github.com/samba-team/samba/blob/24fb40a812184fa57458ae9f0f4ffbced1dee09a/source3/smbd/mangle_hash2.c#L707</a></p>