#!/bin/bash

##############################################################################
# This file is part of the CRYPTO BONE
# File     : safewebdropcrosscontact   (server) 
# Version  : 1.6 (ALL-IN-ONE)
# License  : BSD
# Date     : 12 May 2023
# Contact  : Please send enquiries and bug-reports to innovation@senderek.ie
#
# Copyright (c) 2015-2023
#	Ralf Senderek, Ireland.  All rights reserved. (https://senderek.ie)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this software
#    must display the following acknowledgement:
#	   This product includes software developed by Ralf Senderek.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND  ANY EXPRESS OR 
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  IMPLIED WARRANTIES 
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.
##############################################################################


#----------------------------------------------------#
# load functions and global variables
. ./safewebdrop-functions

function clean {
     rm -f ${FILE} 2> /dev/null
     rm -f ${SIGNED} 2> /dev/null
     rm -f ${VERIFIED} 2> /dev/null
}
#----------------------------------------------------#


/usr/bin/echo Content-type: text/html
/usr/bin/echo

ID=""
REQ=""
# extract ID  and REQ, HASHSIG and PUBKEY
OLDIFS="${IFS}"
IFS=\&
set -- $QUERY_STRING 
ID=$1
REQ=$2
HASHSIG=$3
KEY=$4
IFS=${OLDIFS}

# get the IP
IP=$REMOTE_ADDR

# check if a valid user exists
check_userid ${ID}

LOG=${DEST}/${ID}/log

# make sure the contact directory exists and is accessible for the webserver
if [[ ! -d  ${DEST}/${ID}/contacts ]] ; then
     /usr/bin/mkdir -p ${DEST}/${ID}/contacts
     /usr/bin/chown apache ${DEST}/${ID}/contacts
fi

# to save the state for this request
FILE=${DEST}/${ID}/permission   

log "--- cross contact request ---"
# request = CONTACT or it consists of signed data

if [[ ${REQ} = "CONTACT" ]]; then
     # phase 1
     log "create a new safewebdrop contact request"
     generate_challenge
     return_challenge
else     
     # phase 2
     log "signed request plus sender's pubkey"
     # load the stored credentials
     if [[ -r ${FILE} ]] ; then
          .  ${FILE}
     fi
     
     # check if new request has same ADDR
     if [[ ${IP} != ${ADDR}  ]] ; then
         # dismiss this request
	 clean
         exit 4
     fi

     # extract the SENDER's new PUBKEY without activation
     PUBKEY="${DEST}/${ID}/contacts/SENDER.pubkey.pending"
     /usr/bin/echo -n "${KEY}" | /usr/bin/base64 -d > ${PUBKEY}
     # maybe an allow is present for this CONTACT, then activate this pubkey
     log "writing sender's pubkey to ${PUBKEY}"

     # verify the signature
     verify_request
     # signature is OK

     # split the request
     OLDIFS="${IFS}"
     IFS=\:
     set -- ${REQ} 
     WCHL=$1
     WSENDER=$2
     CONTACTHASH=$3
     IFS=${OLDIFS}

     /usr/bin/mv ${DEST}/${ID}/contacts/SENDER.pubkey.pending ${DEST}/${ID}/contacts/${WSENDER}.pubkey.pending
     PUBKEY="${DEST}/${ID}/contacts/${WSENDER}.pubkey.pending"

     if [[  ${WCHL} != ${CHALLENGE} ]]  ; then
          # request failed
	  log "request ${WREQ} failed $(/usr/bin/date +'%x %X')"
          clean
	  exit 3
     fi
     
     # safe the hash 
     if (( ${#CONTACTHASH} == 64 ))  ; then
          /usr/bin/echo -n ${CONTACTHASH} > ${DEST}/${ID}/contacts/${WSENDER}.request
	  log "contact request written to ${DEST}/${ID}/contacts/${WSENDER}.request"
          /usr/bin/echo -n "OK"
          log "--- end cross contact request ---"
     else
          /usr/bin/echo -n "failed"
	  clean
	  exit 3
     fi
fi     

# now check if an allowance is already stored
if [[ -s ${DEST}/${ID}/contacts/${WSENDER}.allow ]] ; then
     /usr/bin/diff ${DEST}/${ID}/contacts/${WSENDER}.allow ${DEST}/${ID}/contacts/${WSENDER}.request 2>/dev/null >/dev/null
     if (( $? == 0 )) ; then
          log "checking the allow file ${WSENDER}.allow"
          log "request and allow matches for ${WSENDER}. PUBKEY registered!"
          /usr/bin/mv ${DEST}/${ID}/contacts/${WSENDER}.pubkey.pending ${DEST}/${ID}/contacts/${WSENDER}.pubkey.pem
          /usr/bin/rm -f ${DEST}/${ID}/contacts/${WSENDER}.allow ${DEST}/${ID}/contacts/${WSENDER}.request 2>/dev/null >/dev/null
     else
          log "request and allow DO NOT MATCH for ${WSENDER}."
     fi
else
     log "no allowance for ${WSENDER} yet"
fi

clean
exit 0
