/*
 *
  ***** BEGIN LICENSE BLOCK *****

  Copyright (C) 2024 Olof Hagsand and Rubicon Communications, LLC(Netgate)

  This file is part of CLIXON.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  Alternatively, the contents of this file may be used under the terms of
  the GNU General Public License Version 3 or later (the "GPL"),
  in which case the provisions of the GPL are applicable instead
  of those above. If you wish to allow use of your version of this file only
  under the terms of the GPL, and not to allow others to
  use your version of this file under the terms of Apache License version 2,
  indicate your decision by deleting the provisions above and replace them with
  the  notice and other provisions required by the GPL. If you do not delete
  the provisions above, a recipient may use your version of this file under
  the terms of any one of the Apache License version 2 or the GPL.

  ***** END LICENSE BLOCK *****

  Restconf event stream implementation.
  See RFC 8040  RESTCONF Protocol
  Sections 3.8, 6, 9.3

  RFC8040:
   A RESTCONF server MAY send the "retry" field, and if it does, RESTCONF
   clients SHOULD use it.  A RESTCONF server SHOULD NOT send the "event"
   or "id" fields, as there are no meaningful values. RESTCONF
   servers that do not send the "id" field also do not need to support
   the HTTP header field "Last-Event-ID"

   The RESTCONF client can then use this URL value to start monitoring
   the event stream:

      GET /streams/NETCONF HTTP/1.1
      Host: example.com
      Accept: text/event-stream
      Cache-Control: no-cache
      Connection: keep-alive

   The server MAY support the "start-time", "stop-time", and "filter"
   query parameters, defined in Section 4.8.  Refer to Appendix B.3.6
   for filter parameter examples.

 */

#ifdef HAVE_CONFIG_H
#include "clixon_config.h" /* generated by config & autoconf */
#endif

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <syslog.h>
#include <fcntl.h>
#include <time.h>
#include <limits.h>

#include <signal.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <libgen.h>

/* cligen */
#include <cligen/cligen.h>

/* clixon */
#include <clixon/clixon.h>

#include "restconf_lib.h"
#include "restconf_handle.h"
#include "restconf_api.h"
#include "restconf_err.h"
#include "restconf_stream.h"

/*! Check if uri path denotes a stream/notification path
 *
 * @retval     1    Yes, a stream path
 * @retval     0    No, not a stream path
 */
int
api_path_is_stream(clixon_handle h)
{
    int    retval = 0;
    char  *path = NULL;
    char  *stream_path;

   if ((path = restconf_uripath(h)) == NULL)
       goto done;
   if ((stream_path = clicon_option_str(h, "CLICON_STREAM_PATH")) == NULL)
       goto done;
   if (strlen(path) < 1 + strlen(stream_path)) /* "/" + stream */
       goto done;
   if (path[0] != '/')
       goto done;
   if (strncmp(path+1, stream_path, strlen(stream_path)) != 0)
       goto done;
    retval = 1;
 done:
    if (path)
        free(path);
    return retval;
}

/*! Send subscription to backend
 *
 * @param[in]  h         Clixon handle
 * @param[in]  req       Generic Www handle (can be part of clixon handle)
 * @param[in]  name      Stream name
 * @param[in]  qvec
 * @param[in]  pretty    Pretty-print json/xml reply
 * @param[in]  media_out Restconf output media
 * @param[out] sp        Socket -1 if not set (only fcgi)
 * @retval     0    OK
 * @retval    -1    Error
 */
int
restconf_subscription(clixon_handle  h,
                      void          *req,
                      char          *name,
                      cvec          *qvec,
                      int            pretty,
                      restconf_media media_out,
                      int           *sp)
{
    int     retval = -1;
    cxobj  *xret = NULL;
    cxobj  *xe;
    cbuf   *cb = NULL;
    int     s; /* socket */
    int     i;
    cg_var *cv;
    char   *vname;

    clixon_debug(CLIXON_DBG_STREAM, "");
    *sp = -1;
    if ((cb = cbuf_new()) == NULL){
        clixon_err(OE_XML, errno, "cbuf_new");
        goto done;
    }
    cprintf(cb, "<rpc xmlns=\"%s\" %s><create-subscription xmlns=\"%s\"><stream>%s</stream>",
            NETCONF_BASE_NAMESPACE, NETCONF_MESSAGE_ID_ATTR, EVENT_RFC5277_NAMESPACE, name);
    /* Print all fields */
    for (i=0; i<cvec_len(qvec); i++){
        cv = cvec_i(qvec, i);
        vname = cv_name_get(cv);
        if (strcmp(vname, "start-time") == 0){
            cprintf(cb, "<startTime>");
            cv2cbuf(cv, cb);
            cprintf(cb, "</startTime>");
        }
        else if (strcmp(vname, "stop-time") == 0){
            cprintf(cb, "<stopTime>");
            cv2cbuf(cv, cb);
            cprintf(cb, "</stopTime>");
        }
    }
    cprintf(cb, "</create-subscription></rpc>]]>]]>");
    if (clicon_rpc_netconf(h, cbuf_get(cb), &xret, &s) < 0)
        goto done;
    if ((xe = xpath_first(xret, NULL, "rpc-reply/rpc-error")) != NULL){
        if (api_return_err(h, req, xe, pretty, media_out, 0) < 0)
            goto done;
        goto ok;
    }
    /* Setting up stream */
    if (restconf_reply_header(req, "Server", "clixon") < 0)
        goto done;
    if (restconf_reply_header(req, "Content-Type", "text/event-stream") < 0)
        goto done;
    if (restconf_reply_header(req, "Cache-Control", "no-cache") < 0)
        goto done;
    /* HTTP/2 does not use the Connection header field RFC 9113
     * filtered in restconf_reply_header
     */
    if (restconf_reply_header(req, "Connection", "keep-alive") < 0)
        goto done;
    /* Must be there for FCGI caching */
    if (restconf_reply_header(req, "X-Accel-Buffering", "no") < 0)
        goto done;
    if (restconf_reply_send(req, 201, NULL, 0) < 0)
        goto done;
    *sp = s;
 ok:
    retval = 0;
 done:
    clixon_debug(CLIXON_DBG_STREAM, "retval: %d", retval);
    if (xret)
        xml_free(xret);
    if (cb)
        cbuf_free(cb);
    return retval;
}

/*! Process a stream request
 *
 * @param[in]  h       Clixon handle
 * @param[in]  req     Generic Www handle (can be part of clixon handle)
 * @param[in]  qvec    Query parameters, ie the ?<id>=<val>&<id>=<val> stuff
 * @param[in]  timeout Stream timeout
 * @param[out] finish  Set to zero, if request should not be finnished by upper layer
 * @retval     0       OK
 * @retval    -1       Error
 */
int
api_stream(clixon_handle h,
           void         *req,
           cvec         *qvec,
           int           timeout,
           int          *finish)
{
    int            retval = -1;
    char          *path = NULL;
    char         **pvec = NULL;
    int            pn;
    cvec          *pcvec = NULL; /* for rest api */
    cxobj         *xerr = NULL;
    char          *streampath;
    int            pretty;
    int            besock = -1;
    restconf_media media_reply = YANG_DATA_XML;
    char          *media_list = NULL;
    char          *stream_name;
    int            ret;

    clixon_debug(CLIXON_DBG_STREAM, "");
    if (req == NULL){
        clixon_err(OE_RESTCONF, EINVAL, "req is NULL");
        goto done;
    }
    streampath = clicon_option_str(h, "CLICON_STREAM_PATH");
    if ((path = restconf_uripath(h)) == NULL)
        goto done;
    pretty = restconf_pretty_get(h);
    if ((pvec = clicon_strsep(path, "/", &pn)) == NULL)
        goto done;
    /* Sanity check of path. Should be /stream/<name> */
    if (pn != 3){
        if (netconf_invalid_value_xml(&xerr, "protocol", "Invalid path, /stream/<name> expected") < 0)
            goto done;
        if (api_return_err0(h, req, xerr, pretty, media_reply, 0) < 0)
            goto done;
        goto ok;
    }
    /* Get media for output (proactive negotiation) RFC7231 by using
     */
    if ((media_list = restconf_param_get(h, "HTTP_ACCEPT")) == NULL){
        if (restconf_not_acceptable(h, req, pretty, media_reply) < 0)
            goto done;
        goto ok;
    }
    /* Accept only text_event-stream or */
    if (restconf_media_in_list("text/event-stream", media_list) != 1 &&
        restconf_media_in_list("*/*", media_list) != 1) {
        if (restconf_not_acceptable(h, req, pretty, media_reply) < 0)
            goto done;
        goto ok;
    }
    if (strlen(pvec[0]) != 0){
        if (netconf_invalid_value_xml(&xerr, "protocol", "Invalid path, /stream/<name> expected") < 0)
            goto done;
        if (api_return_err0(h, req, xerr, pretty, media_reply, 0) < 0)
            goto done;
        goto ok;
    }
    if (strcmp(pvec[1], streampath)){
        if (netconf_invalid_value_xml(&xerr, "protocol", "Invalid path, /stream/<name> expected") < 0)
            goto done;
        if (api_return_err0(h, req, xerr, pretty, media_reply, 0) < 0)
            goto done;
        goto ok;
    }
    if ((stream_name = pvec[2]) == NULL){
        if (netconf_invalid_value_xml(&xerr, "protocol", "Invalid path, /stream/<name> expected") < 0)
            goto done;
        if (api_return_err0(h, req, xerr, pretty, media_reply, 0) < 0)
            goto done;
        goto ok;
    }
    clixon_debug(CLIXON_DBG_STREAM, "stream-name: %s", stream_name);
    if (uri_str2cvec(path, '/', '=', 1, &pcvec) < 0) /* rest url eg /album=ricky/foo */
        goto done;
    /* If present, check credentials. See "plugin_credentials" in plugin
     * See RFC 8040 section 2.5
     */
    if ((ret = restconf_authentication_cb(h, req, pretty, media_reply)) < 0)
        goto done;
    if (ret == 0)
        goto ok;
    if (restconf_subscription(h, req, stream_name, qvec, pretty, media_reply, &besock) < 0)
        goto done;
    if (besock != -1){
        if (stream_sockets_setup(h, req, timeout, besock, finish) < 0)
            goto done;
    }
 ok:
    retval = 0;
 done:
    clixon_debug(CLIXON_DBG_STREAM, "retval:%d", retval);
    if (xerr)
        xml_free(xerr);
    if (pvec)
        free(pvec);
    if (pcvec)
        cvec_free(pcvec);
    if (path)
        free(path);
    return retval;
}
