/*  */
aliascfg:
CHECKIT=0   /* Change this to 0 if you want to enable REMOTE configuration */

/* background color */
USECOLOR='2dd52f'


/* ---------------- DO NOT MODIFY BELOW THIS LINE  ------------------ */

parse arg  ddir, tempfile, sel,list,verb ,uri,user, ,
          basedir ,workdir,privset,enmadd,transaction,verbose, ,
         servername,host_nickname,homedir,aparam,semqueue,prog_file,reqnum

/* parse arg ddir,tempfile,sel,list,verb,uri,user,basedir,workdir,privset, ,
  enmadd,transaction,verbose */

if verb="" then do
   say " This SRE-http add-on is NOT meant to be run from the command line."
   say " It can be invoked by using CONFIGUR.HTM "
   exit
end  /* Do */


list=translate(list, ' ', '+'||'090a0d'x)  /* Whitespace, etc. */

who2=extract('CLIENTADDR')
saddr2=extract('SERVERADDR')
crlf='0d0a'x

NO_REM=VALUE('SREF_NO_REMOTE_CONFIG',,'OS2ENVIRONMENT')

select
   when checkit=1 | no_rem>0 then do

/* only if user = serveraddress !!! */
     if who2<>saddr2 | no_rem=2 then do

        call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
        call lineout tempfile, "<html><head><title>SRE-http  remote configurator disabled </title>"
        call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'

        call lineout tempfile,' <strong> Action not allowed remotely.</strong> <pre>'
        call lineout tempfile,' </body> </html> '
        call lineout tempfile
        foo=sref_gos('FILE ERASE TYPE text/html NAME' tempfile)
        return 'ALIASCFG: action not allowed remotely. '
     end
   end
   otherwise do
      if wordpos('SUPERUSER',privset)=0 then do
        'RESPONSE HTTP/1.1 401 Unauthorized '     /* Set HTTP response line */
        att=sref_gmt()
        'HEADER Noauto ADD Date: 'att
        'header add WWW-Authenticate: Basic Realm=<CONFIGURE>'  /* challenge */

        call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
        call lineout tempfile, "<html><head><title>Not authorized </title>"
        call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'


        call lineout tempfile,' <strong> You do not have configuration rights.</strong> <pre>'
        if who2=saddr2 then 
                call lineout tempfile,'<br> <Em> You may want to edit USERCFG.CMD </em> '
        call lineout tempfile,' </body> </html> '
        call lineout tempfile
         iia=dosdir(tempfile,'s')
        'FILE ERASE TYPE text/html NAME' tempfile
        return '401 'iia' ALIASCFG: not permitted to configure. '
      end
   end
end

list=strip(list)
select 
   when upper(list)='TODO=SHOW' | upper(list)='TODO=SHOW_HEADER' then
        signal doshow

   when upper(list)='TODO=CURRENT' then
        signal showcurrent

   when upper(list)='TODO=PUBURLS' then
        signal showcurrent_puburls

   when upper(list)='TODO=SET' then
        signal doset
   otherwise
        signal dochange
end  /* select */

/* jump here to show values */
doshow:

aliasfile=value(enmadd||'ALIAS_FILE',,'os2environment')
   call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
   call lineout tempfile, "<html><head><title>SRE-http redirection aliases </title>"
   call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'


aa=go_fileread(aliasfile)  /* expose lins */

/*aa=fileread(aliasfile,'lins',,'E') */

call lineout tempfile, "<h1> SRE-http: <A NAME="top"> Redirection aliases </A>   </h1> <p>"
if upper(list)="TODO=SHOW"  then
   call lineout tempfile, "<h2> List of "header" comments </h2> <pre> <blockquote>"
else
   call lineout tempfile, "<h2> Description of redirection aliaases </h2> <pre> <blockquote>"


/* show "header comments" */
iat=0
do until iat >= lins.0
   iat=iat+1
   if  abbrev(strip(lins.iat),';')  then do
        foo=strip(lins.iat) ;foo=strip(foo,'l',';')
         call lineout tempfile, foo 
   end  /* Do */
   else do
        leave
   end
end /* do -- iat is the first non header comment line  */
call lineout tempfile, '</blockquote></pre> '

/* view descriptive header only? */
if upper(list)='TODO=SHOW_HEADER' then do
   call lineout tempfile,' <hr> </body></html>'
   call lineout tempfile
   foo=sref_gos('file erase  type text/html name  ' tempfile)
   return ' done '
end  /* Do */

/* read in aliases, etc */
nusers=0
call lineout tempfile, '<hr><h2> List of redirection aliases </h2> '
call lineout tempfile,' Notes: <ul> '
call lineout tempfile,' <li> Aliases are stored in: ' aliasfile
call lineout tempfile,' <li> <em>Comments are in italics </em> '
call lineout tempfile,' <li> The <strong>*</strong> character is used as a wildcard (for an arbitrarily long string)'
call lineout tempfile, ' <li> Entries with no <strong>host nickname</strong> apply to all requests</ul> <br>'
call lineout tempfile,' <table border=1> <th> Host Nickname </th>'
call lineout tempfile,' <th> Candidate SEL (convert from)</th>'
call lineout tempfile,'  <th> Target of redirection (convert to) </th> <tr>'

do mm=iat to lins.0
  if lins.mm=' ' then iterate
  if  abbrev(strip(lins.mm),';') then do  
       call lineout tempfile,'<td colspan=3>  <code>     </code> <em>' strip(strip(lins.mm),'l',';') '</em></td> <tr> '
  end
  else do
      if pos('// ',lins.mm)>0 then do
           parse var lins.mm hostname '//' candurl targurl
      end
      else do
           hostname=' .. '
           parse var lins.mm candurl targurl
      end  /* Do */
      movers=' '
      if abbrev(upper(targurl),'!MOVED')+abbrev(upper(targurl),'!TEMP')>0 then do
           parse var targurl movers targurl
      end /* do */

      if length(targurl) > 55 then do
          iiat2=0 ; moocow='' ; ijoe=length(targurl) 
          do while iiat2 <= length(targurl)
              iiat=iiat2+1
              eek=substr(targurl,iiat,45)
              moocow=moocow||eek||'<br>'
              iiat2=iiat2+45
          end
          targurl=moocow
      end
      call lineout tempfile,'<td>   &nbsp; <STRONG> 'hostname '</STRONG> </td>'
      call lineout tempfile,'<td> &nbsp; <STRONG> ' candurl '</STRONG> </td>'
      call lineout tempfile,'<td>  &nbsp; <STRONG> 'movers ' 'targurl '</STRONG> </td> <tr>'

  end /* do */

end
call lineout tempfile,' </table>'

call lineout tempfile,' <hr> Thanks for checking </body></html>'
call lineout tempfile

foo=sref_gos('file erase  type text/html name  ' tempfile)
return ' done '


/* jump here if "show current" chosen */
showcurrent:
foo=wait_queue('ALIAS')
call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
call lineout tempfile, "<html><head><title>SRE-http: list of aliases </title>"
call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'

call lineout tempfile, '<h2>List of SRE-http ALIASes </h2>'
call lineout tempfile,' This complete list of ALIASes includes entries in default and host specific copies '
call lineout tempfile,' of ALIASES.IN and ATTRIBS.CFG <hr width="30%">'
call lineout tempfile,'<table border=1>'
call lineout tempfile,'<tr><th> Host <th> Selector <th> Replacement '
do forever
  if foo='' then leave
  parse var foo ah '//' a1 a2 (crlf) foo
  call lineout tempfile,'<tr><td> 'ah '<td> 'a1 '<td> 'a2 
end
call lineout tempfile,'</table></body></html>'
call lineout tempfile
foo=sref_gos('file erase  type text/html name  ' tempfile)
return ' done '

  

/* jump here if "show current puburls" chosen */
showcurrent_puburls:
foo=wait_queue('PUBURL')
call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
call lineout tempfile, "<html><head><title>SRE-http: list of Public URLS</title>"
call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'

call lineout tempfile, '<h2>List of SRE-http Public URLS</h2>'
call lineout tempfile,' This complete list of Public URLS includes entries in default and host specific copies '
call lineout tempfile,' of PUBURLS.IN and ATTRIBS.CFG <hr width="30%">'
call lineout tempfile,'<table border=1>'
call lineout tempfile,'<tr><th> Host <th> Selector <th> Options '
do forever
  if foo='' then leave
  parse var foo aline (crlf) foo
  parse var aline ah '//' a1 a2
  call lineout tempfile,'<tr><td> 'ah '<td> 'a1 '<td> 'a2 
end
call lineout tempfile,'</table></body></html>'
call lineout tempfile
foo=sref_gos('file erase  type text/html name  ' tempfile)
return ' done '

  



/* --- jump here to modify values -- */
/* jump here if "set values" chosen */
doset:
aliasfile=value(enmadd||'ALIAS_FILE',,'os2environment')

aa=go_fileread(aliasfile)
/*aa=fileread(aliasfile,'lins',,'E')*/

call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
call lineout tempfile, "<html><head><title>SRE-http: modify redirection aliases </title>"
call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'

call lineout tempfile,'<!--  a button bar. --> 'crlf ,
           '<a href="/configur.htm">Configurator</a>||' crlf ,
           '<a href="/config2?todo=SET">Parameters</a>||' crlf ,
           '<a href="/usercfg?todo=SET">Usernames</a>||'  crlf ,
           '<a href="/realmcfg?todo=SET">Define-Realms</a>||'||crlf ,
           '<a href="/accescfg?todo=SET">Access-Controls||'  crlf ,
           '<a href="/aliascfg?todo=SET">Aliases</a>||'  crlf ,
           '<a href="/virtcfg?todo=SET">VirtualDir</a><p>'  


/* ignore header stuff */
iat=0
do until iat >= lins.0
   iat=iat+1
   if  abbrev(strip(lins.iat),';') | lins.iat=' ' then iterate
   leave
end /* do -- iat is the first non header comment line  */

call lineout tempfile, "<h1> SRE-http: modify redirection Aliases  </h1> <p>"

call lineout tempfile,' <blockquote> You can modify, remove, or add redirection aliases.'
call lineout tempfile,' <br><em> Questions? <A HREF="#notes">The notes might help.</A> </em> </blockquote> '
call lineout tempfile,' <h2> Modify or remove current Aliases </h2>'
call lineout tempfile,'<FORM ACTION="/aliascfg" METHOD="POST">'
call lineout tempfile,' <table border=1> <th> Host Nickname <br> (see below  for a <br>listing of <A HREF="#hosts">current hosts</A>) </th>'
call lineout tempfile,' <th> Candidate SEL   (set to blank to  <br> delete the entry)</th>'
call lineout tempfile,'  <th> Target SEL   </th> <tr>'

nhidden=0 ; mm=0
do mm0=iat to lins.0
    alin=translate(lins.mm0,' ','1a000d0a'x)
    mm=mm+1
    if  abbrev(strip(alin),';')=1 | alin=' ' then do
        nhidden=nhidden+1
        hiddens.nhidden='<INPUT TYPE="HIDDEN" name="COMMENT.'||mm||'"  value="'||alin||'" >'
        iterate
    end

/* non comment */
    if pos('// ',alin)>0 then
             parse var alin hostname '//' candurl targurl
        else do
             hostname='  '
             parse var alin candurl targurl
     end  /* Do */
     call lineout tempfile,'<td> <EM>Host nickname:</EM> <br> <INPUT TYPE="text" NAME="hostname.'||mm||'"'
     call lineout tempfile,'value="'hostname'" SIZE=8 MAXLENGTH=15> </td> '

/*    call lineout tempfile,'<td> <EM>Candidate SEL:</EM> <br> <INPUT TYPE="text" NAME="candurl.'||mm||'"'
     call lineout tempfile,'value="'candurl'" SIZE=28 MAXLENGTH=295> </td> '*/

     candurl2=candurl ; iat=25
     do until iat>length(candurl2)
          candurl2=insert('0d0a'x,candurl2,iat)
          iat=iat+30
     end /* do */

     call lineout tempfile,'<td> <EM>Candidate SEL:</EM> <br> <TEXTAREA NAME="candurl.'||mm||'"'
     call lineout tempfile,' rows=2 cols=32>'candurl2' </textarea> </td>'


/*     call lineout tempfile,'<td> <EM>Target SEL:</EM> <br> <INPUT TYPE="text" NAME="targurl.'||mm||'"'
     call lineout tempfile,'value="'targurl'" SIZE=28 MAXLENGTH=295> </td> '*/
     targurl2=targurl ; iat=25
     do until iat>length(targurl2)
          targurl2=insert('0d0a'x,targurl2,iat)
          iat=iat+35
     end /* do */
     call lineout tempfile,'<td> <EM>Target SEL:</EM> <br> <TEXTAREA NAME="targurl.'||mm||'"'
     call lineout tempfile,' rows=2 cols=35>'targurl2'</textarea> </td>'


     if mm0<lins.0 then do
           call lineout tempfile,'<tr>' ; call lineout tempfile,' '
     end
end
call lineout tempfile,' '

/* --- allow user to enter a few new names */
call lineout tempfile,' </table>  <p> <h2> Add new redirection aliases </h2> <table border=1>'
mm0=mm
do mm=mm0+1 to mm0+3
     call lineout tempfile,'<td> <EM>Host nickname:</EM> <br> <INPUT TYPE="text" NAME="hostname.'||mm||'"'
     call lineout tempfile,'value=" " SIZE=8 MAXLENGTH=15> </td> '
     call lineout tempfile,'<td> <EM>Candidate SEL:</EM> <br>'
     call lineout tempfile,'<textarea name="candurl.'||mm||'" rows=2 cols=30>'
     call lineout tempfile,' </textarea> </td> '
     call lineout tempfile,'<td> <EM>Target SEL:</EM> <br>'
     call lineout tempfile,' <TEXTAREA NAME="targurl.'||mm||'" rows=2 cols=30>'
     call lineout tempfile,' </textarea> </td> '
     if mm<mm0+3 then call lineout tempfile,' <tr> '
end

call lineout tempfile,'</table> <p>'


/* ----- add comments information */

do jj=1 to nhidden
   call lineout tempfile,hiddens.jj
end /* do */
call lineout tempfile,' <input type="hidden" name="entries" value="'||mm||'">'
call lineout tempfile,' <input type="submit"> <input type="reset"> </form> '


call lineout tempfile,' <hr> <h3><A NAME="notes"> Notes</A> </h3> '
call lineout tempfile,' <ul> <li> Aliases are stored in: 'aliasfile
call lineout tempfile,' <li> New lines and spaces, that are included in '
call lineout tempfile,' <em>candidate sel </em> and <em>target sel </em> fields, '
call lineout tempfile,' will be removed.'
call lineout tempfile,' <li> If a <em>request selector</em> matches a <em>candidate SEL</em>, '
call lineout tempfile,' <br> the associated <em>target SEL </em> is for the (internal or external) redirection'
call lineout tempfile,' <li> To add more then 3 new aliases, just rerun this several times <br> or edit ' aliasfile
call lineout tempfile,' <li> Do you want to view a  more complete description of '
call lineout tempfile,' <a href="/samples/in_files.doc"> aliases </a>?'
call lineout tempfile,' <li>View the <a href="/aliascfg?TODO=CURRENT"> current set of aliases </a>?'

call lineout tempfile,' <li> <em>Comments are NOT displayed </em>  <li> Case is ignored '
call lineout tempfile,' <li> Use a <strong>* </strong> in the <em>candidate SEL</em> as a wildcard character '
call lineout tempfile,' <li> When a * appears in the <em>candidate SEL</em>.. '
call lineout tempfile,' <br> you can use a <strong>* </strong> in the <em>target SEL</em> as a placeholder for the wildcard match '
call lineout tempfile,' <li> A <em>Target SEL</em> being used for external redirection should start with <strong>http:// </strong>'
call lineout tempfile, ' <li> Entries with no <strong>host nickname</strong> will apply to all requests'
call lineout tempfile, ' <li> To identify a negotiable resource, enter <B>!NEGOTIATE</b> in the ',
                       ' <em>Target sel </em> field<br>'
call lineout tempfile,' <em> Or, </em> enter <B>!NEGOTIATE variant_list</b>, and use a wildcarded <em>candidate sel</em></ul> <br>'



call lineout tempfile,' <h3> A list of the <A NAME="hosts">current hosts</A> </h3>  <blockquote> '
ii=value(enmadd||'HOSTS.0',,'os2environment')
if ii=0 then do
   call lineout tempfile,'<strong>There are no hosts defined</strong>'
end 
else do
  hlist=sref_value('$HOSTS.0',,'USE')
  call lineout tempfile,' <table> <th> IP address </th> <th> Host Nickname </th> <th> Data Directory </th> <tr> '
  do ll=1 to words(hlist)
      hh=strip(translate(word(hlist,ll)))
      wow=sref_value('$HOSTS.'||hh,,'use')
      parse var wow ip ',' hn ',' hdir
     call lineout tempfile,' <td> ' ip  '</td> <td> ' hn ' </td> <td> ' hdir '</td> <tr> '
  end /* do */
  call lineout tempfile,' </table> </blockquote>'
end


call lineout tempfile,' <p> <A HREF="#top">Return to the top of this form.</A>'

call lineout tempfile,'</body></html>'
call lineout tempfile

foo=sref_gos('file erase  type text/html name  ' tempfile)
return foo



/* ********************** jump here to recrod changes */
dochange:

parse upper var list foo 'ENTRIES=' nentries '&' .
do ii1=1 to nentries
   fillme.ii1.0=0
end /* do */

do until list=""
   parse var list aa '&' list
   parse  var aa avar '.' aind '=' aval
   avar=upper(avar)
   aval=packur(aval)
   if abbrev(upper(avar),'ENTRIES=')=1 then iterate
   wow=fillme.aind.0+1
   fillme.aind.0=wow
   fillme.aind.wow.var=avar ; fillme.aind.wow.val=aval
   select
      when avar="COMMENT" then do
          fillme.aind.type='COMMENT'
          parse  var aa foo '=' aval
          fillme.aind.wow.val=packur(aval)
      end
      when avar="CANDURL" then fillme.aind.type='URL'
      otherwise nop
   end
end /* do */

aliasfile=value(enmadd||'alias_FILE',,'os2environment')
aa=go_fileread(aliasfile)
/*aa=fileread(aliasfile,'lins',,'E')*/

/* pull "header comments" */
iat=0
do until iat >= lins.0
   iat=iat+1
   if  abbrev(strip(lins.iat),';')=1  then do
       newlines.iat=lins.iat
   end  /* Do */
   else do
        leave
   end
end /* do -- iat is the first non header comment line  */
iat=iat-1

do uu=1 to nentries
   select
      when fillme.uu.type='COMMENT' then do
          iat=iat+1
          newlines.iat=fillme.uu.1.val
      end
      when fillme.uu.type='URL' then do
          candurl=' ' ; targurl=' ' ; hostname=' ' 
          do uu2=1 to fillme.uu.0
             chk1=fillme.uu.uu2.var
             vvv=strip(fillme.uu.uu2.val)
             prefx=''

             if abbrev(vvv,'!')>0 then do
                 parse var vvv vvva vvvb ; vvva=strip(upper(vvva))
                 if wordpos(vvva,'!TEMP !NEGOTIATE !MOVED')>0 then do
                     prefx=vvva' ' ; vvv=vvvb
                 end

             end /* do */
             vvv2=prefx' 'space(translate(vvv,' ','0d0a'x),0)
             select
                when chk1='CANDURL' then candurl=vvv2
                when chk1='TARGURL' then targurl=vvv2
                when chk1='HOSTNAME' then hostname=vvv
                otherwise nop
             end
             
          end
          if candurl<>' ' then do
              iat=iat+1
              newlines.iat=''
              if hostname<>' ' then
                  newlines.iat=hostname||'// '
              newlines.iat=newlines.iat||candurl' ' targurl
          end
      end
      otherwise do
            nop
      end  /* Do */

  end                   /* select over type */
end                     /* do over entries */

/* save to aliasfile.. but rename access_file first */
foo=lastpos('.',aliasfile)
if FOO=0 then
   acf1=aliasfile||'.'
else
   acf1=left(aliasfile,foo)
do hi=1 to 999
   try1=acf1||hi
   if stream(acf1||hi,'c','query exists')='' then leave
end /* do */
foo=dosrename(aliasfile,try1)


newlines.0=iat
foo=sref_filewrite(aliasfile,newlines,'R')


call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
call lineout tempfile, "<html><head><titLE> SRE-http: Changed the aliases</title>"
call lineout tempfile, '</head><body  bgcolor="#'||usecolor||'">'

call lineout tempfile,' <h2>The aliases have been changed </h2>'
call lineout tempfile,' The list of aliases has been saved to: ' aliasfile
call lineout tempfile,' <p> The old version of 'aliasfile' has been moved to ' try1
call lineout tempfile,'<p> <a href="/config2.htm">Return to Intermediate Mode Configurator</a>'

call lineout tempfile,' </body> </html> '
call lineout tempfile

foo=value('SREF_REDO',1,'os2environment')

foo=sref_gos('FILE ERASE TYPE text/html NAME' tempfile)
return 'done change '




/* read in aliasfile, concatenate  extension lines */
go_fileread:procedure expose lins.
parse arg aliasfile
aa=sref_fileread(aliasfile,'lins0',,'E')
FOO=DO_EXTENDS(0)


/* OLDER "END WITH , " METHOD RETAINED FOR COMPATABILITIES */
ill=0
exton=0
do il=1 to lins0.0
  t1=strip(lins0.il)
  if exton=1 then do
       t1=t1storage||t1
  end
  exton=0 

  if abbrev(t1,';')=0 then do
     if right(t1,2)=' ,' & il < lins0.0 then do
        exton=1
        t1=left(t1,length(t1)-2)
        t1storage=strip(t1)
        iterate
     end
  end

  ill=ill+1
  lins.ill=t1
end /* do */

lins.0=ill
return ill


/************/
/* Redo ulist, by treating lines starting with , as continuation lines */
do_extends:procedure expose lins0.

if lins0.0=0 then return
isnew=1
tmps.1=lins0.1
do mm=2 to lins0.0
   ali=strip(lins0.mm)
   if abbrev(ali,',')=0 then do
        isnew=isnew+1
        tmps.isnew=lins0.mm
    end
    else do
        tmps.isnew=tmps.isnew||substr(ali,2)
    end
end
do mm=1 to isnew
    lins0.mm=tmps.mm
end
lins0.0=isnew
return 0


/* ------------------------------------------------------ */
/* query and wait on helper thread */
/* ------------------------------------------------------*/
wait_queue:procedure expose enmadd transaction semqueue host_nickname
parse arg athread
again1t:

parse var semqueue mysem myqueue

basesem='\SEM32\'||enmadd

goober=enmadd||athread
 a=rxqueue('s',goober)
 queue  transaction ' ' host_nickname ',' myqueue ',' mysem ', *LIST* '

  a=eventsem_reset(mysem)
  dothread=basesem||athread

  a=eventsem_post(dothread)
again2t:
  a=eventsem_wait(mysem,90000)  /* max wait of 90 seconds */

  if a<>0 then do
        ss=sref_error(mytid','athread' A Fatal Semaphore failure: 'a,1)
        'response HTTP/1.1 503 Service Unavailable'
        String 'Web server is temporarily busy '
        exit ' '
  end
  a=rxqueue('s',myqueue)

  parse pull aline

  PARSE VAR ALINE idnum ',' aline
  idnum=strip(translate(idnum,' ','000d0a'x));TRANSACTION=STRIP(TRANSACTION)
  if idnum<>transaction then  do /*wierd error: got someone else's message! */
        ss=sref_error(mytid','athread' A  Semaphore failure: 'a,1)
        'response HTTP/1.1 503 Service Unavailable'
        String 'Web server is temporarily busy '
        exit ' '
  end

  return aline



