/***
  This file is part of avahi.

  avahi is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1 of the
  License, or (at your option) any later version.

  avahi is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
  Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with avahi; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  USA.
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>

#include <avahi-common/domain.h>
#include <avahi-common/timeval.h>
#include <avahi-common/malloc.h>
#include <avahi-common/error.h>

#include "browse.h"
#include "log.h"

#define TIMEOUT_MSEC 5000

struct AvahiSHostNameResolver {
    AvahiServer *server;
    char *host_name;

    AvahiSRecordBrowser *record_browser_a;
    AvahiSRecordBrowser *record_browser_aaaa;

    AvahiSHostNameResolverCallback callback;
    void* userdata;

    AvahiRecord *address_record;
    AvahiIfIndex interface;
    AvahiProtocol protocol;
    AvahiLookupResultFlags flags;

    AvahiTimeEvent *time_event;

#ifdef HAVE_BONJOUR
    AvahiTimeEvent *defer_time_event;
    AvahiWatch *watch_a;
    AvahiWatch *watch_a6;
    AvahiLookupFlags lookup_flags;
    DNSServiceRef client_a;
    DNSServiceRef client_a6;
#endif

    AVAHI_LLIST_FIELDS(AvahiSHostNameResolver, resolver);
};

static void finish(AvahiSHostNameResolver *r, AvahiResolverEvent event) {
    assert(r);

    if (r->time_event) {
        avahi_time_event_free(r->time_event);
        r->time_event = NULL;
    }

    switch (event) {
        case AVAHI_RESOLVER_FOUND: {
            AvahiAddress a;

            assert(r->address_record);

            switch (r->address_record->key->type) {
                case AVAHI_DNS_TYPE_A:
                    a.proto = AVAHI_PROTO_INET;
                    a.data.ipv4 = r->address_record->data.a.address;
                    break;

                case AVAHI_DNS_TYPE_AAAA:
                    a.proto = AVAHI_PROTO_INET6;
                    a.data.ipv6 = r->address_record->data.aaaa.address;
                    break;

                default:
                    abort();
            }

            r->callback(r, r->interface, r->protocol, AVAHI_RESOLVER_FOUND, r->address_record->key->name, &a, r->flags, r->userdata);
            break;

        }
  
        case AVAHI_RESOLVER_FAILURE:

            r->callback(r, r->interface, r->protocol, event, r->host_name, NULL, r->flags, r->userdata);
            break;
    }
}

#ifdef HAVE_BONJOUR
static void resolve_socket_event(AvahiWatch *w, int fd, AvahiWatchEvent events,
void *userdata) {
    AvahiSHostNameResolver *r = userdata;
    DNSServiceErrorType ret;
    DNSServiceRef client;

    assert(w);
    assert(fd >= 0);
    assert(events & AVAHI_WATCH_IN);

    if (fd == DNSServiceRefSockFD(r->client_a))
        client = r->client_a;
    else if (fd == DNSServiceRefSockFD(r->client_a6))
        client = r->client_a6;
    else
        assert (0);

    ret = DNSServiceProcessResult(client);
    if (ret != kDNSServiceErr_NoError) {
        if (client == r->client_a) {
            if (r->watch_a) {
                r->server->poll_api->watch_free(r->watch_a);
                r->watch_a = NULL;
            }
            DNSServiceRefDeallocate(r->client_a);
            r->client_a = NULL;
        } else if (client == r->client_a6) {
            if (r->watch_a6) {
                r->server->poll_api->watch_free(r->watch_a6);
                r->watch_a6 = NULL;
            }
            DNSServiceRefDeallocate(r->client_a6);
            r->client_a6 = NULL;
        }
        avahi_server_set_errno(r->server, AVAHI_ERR_DISCONNECTED);
        finish(r, AVAHI_RESOLVER_FAILURE);
    }
}

static void resolve_reply(DNSServiceRef client, DNSServiceFlags flags, uint32_t IfIndex, DNSServiceErrorType errorCode, const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void* rdata, uint32_t ttl, void *context) {
    AvahiSHostNameResolver *r = context;
    const unsigned char *rd = rdata;
    AvahiAddress a;

    assert(rrtype == kDNSServiceType_A || rrtype == kDNSServiceType_A6);
    if (!flags & kDNSServiceFlagsAdd)
        /* this is a remove event  so ignore*/
        return;

    if (r->interface > 0  && IfIndex != r->interface)
        return;
    if (r->interface <= 0)
       r->interface = IfIndex;

    /*
     * Using Bonjour we cannot determine whether result was obtained from
     * multicast ot unicast query
     */
    r->flags = 0;

    switch (rrtype) {
        case kDNSServiceType_A:
            if (r->protocol == AVAHI_PROTO_UNSPEC)
                r->protocol = AVAHI_PROTO_INET;
            else if (r->protocol != AVAHI_PROTO_INET)
                return;

            if (!r->address_record) {
                if (!(r->address_record = avahi_record_new_full(r->host_name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_A, ttl))) {
                    avahi_server_set_errno(r->server, AVAHI_ERR_NO_MEMORY);
                    finish(r, AVAHI_RESOLVER_FAILURE);
                    return;
                }
                if (avahi_rdata_parse(r->address_record, rdata, rdlen) != 0) {
                    avahi_server_set_errno(r->server, AVAHI_ERR_INVALID_PACKET);
                    finish(r, AVAHI_RESOLVER_FAILURE);
                }
            }
            break;
        case kDNSServiceType_A6:
            if (r->protocol == AVAHI_PROTO_UNSPEC)
                r->protocol = AVAHI_PROTO_INET6;
            else if (r->protocol != AVAHI_PROTO_INET6)
                return;
            if (!r->address_record) {
                if (!(r->address_record = avahi_record_new_full(r->host_name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_AAAA, ttl))) {
                    avahi_server_set_errno(r->server, AVAHI_ERR_NO_MEMORY);
                    finish(r, AVAHI_RESOLVER_FAILURE);
                    return;
                }
                if (avahi_rdata_parse(r->address_record, rdata, rdlen) != 0) {
                    avahi_server_set_errno(r->server, AVAHI_ERR_INVALID_PACKET);
                    finish(r, AVAHI_RESOLVER_FAILURE);
                    return;
                }
            }
            break;
        default:
            abort();
    }
    finish(r, AVAHI_RESOLVER_FOUND);
}

static void resolve_error_callback(AvahiTimeEvent *e, void *userdata) {
    AvahiSHostNameResolver *r = userdata;

    if (r->defer_time_event) {
        avahi_time_event_free(r->defer_time_event);
        r->defer_time_event = NULL;
    }
    avahi_server_set_errno(r->server, AVAHI_ERR_FAILURE);
    finish(r, AVAHI_RESOLVER_FAILURE);
}

static void avahi_resolve_host_name_start(AvahiSHostNameResolver *r, AvahiProtocol aprotocol)
{
    DNSServiceErrorType ret;
    DNSServiceFlags flags;

    if (r->flags == AVAHI_LOOKUP_USE_MULTICAST)
        flags = kDNSServiceFlagsForceMulticast;

    if (aprotocol == AVAHI_PROTO_INET || aprotocol == AVAHI_PROTO_UNSPEC) {
        ret = DNSServiceQueryRecord(&r->client_a,
                                    flags,
                                    r->interface == AVAHI_IF_UNSPEC ?
                                        kDNSServiceInterfaceIndexAny :
                                        r->interface,
                                    r->host_name,
                                    kDNSServiceType_A,
                                    kDNSServiceClass_IN,
                                    resolve_reply,
                                    r);
        if (ret != kDNSServiceErr_NoError || !r->client_a) {
            r->defer_time_event = avahi_time_event_new(r->server->time_event_queue, NULL, resolve_error_callback, r);
           return;
        } else {
            r->watch_a = r->server->poll_api->watch_new(r->server->poll_api, DNSServiceRefSockFD(r->client_a), AVAHI_WATCH_IN, resolve_socket_event, r);
        }
    }
    if (aprotocol == AVAHI_PROTO_INET6 || aprotocol == AVAHI_PROTO_UNSPEC) {
        ret = DNSServiceQueryRecord(&r->client_a6,
                                    flags,
                                    r->interface == AVAHI_IF_UNSPEC ?
                                        kDNSServiceInterfaceIndexAny :
                                        r->interface,
                                    r->host_name,
                                    kDNSServiceType_AAAA,
                                    kDNSServiceClass_IN,
                                    resolve_reply,
                                    r);
        if (ret != kDNSServiceErr_NoError || !r->client_a6) {
            r->defer_time_event = avahi_time_event_new(r->server->time_event_queue, NULL, resolve_error_callback, r);
           return;
        } else {
            r->watch_a6 = r->server->poll_api->watch_new(r->server->poll_api, DNSServiceRefSockFD(r->client_a6), AVAHI_WATCH_IN, resolve_socket_event, r);
        }
    }
}
#endif

static void time_event_callback(AvahiTimeEvent *e, void *userdata) {
    AvahiSHostNameResolver *r = userdata;

    assert(e);
    assert(r);

    avahi_server_set_errno(r->server, AVAHI_ERR_TIMEOUT);
    finish(r, AVAHI_RESOLVER_FAILURE);
}

static void start_timeout(AvahiSHostNameResolver *r) {
    struct timeval tv;
    assert(r);

    if (r->time_event)
        return;

    avahi_elapse_time(&tv, TIMEOUT_MSEC, 0);

    r->time_event = avahi_time_event_new(r->server->time_event_queue, &tv, time_event_callback, r);
}

#ifndef HAVE_BONJOUR
static void record_browser_callback(
    AvahiSRecordBrowser*rr,
    AvahiIfIndex interface,
    AvahiProtocol protocol,
    AvahiBrowserEvent event,
    AvahiRecord *record,
    AvahiLookupResultFlags flags,
    void* userdata) {

    AvahiSHostNameResolver *r = userdata;

    assert(rr);
    assert(r);


    switch (event) {
        case AVAHI_BROWSER_NEW:
            assert(record);
            assert(record->key->type == AVAHI_DNS_TYPE_A || record->key->type == AVAHI_DNS_TYPE_AAAA);

            if (r->interface > 0 && interface != r->interface)
                return;

            if (r->protocol != AVAHI_PROTO_UNSPEC && protocol != r->protocol)
                return;

            if (r->interface <= 0)
                r->interface = interface;

            if (r->protocol == AVAHI_PROTO_UNSPEC)
                r->protocol = protocol;

            if (!r->address_record) {
                r->address_record = avahi_record_ref(record);
                r->flags = flags;

                finish(r, AVAHI_RESOLVER_FOUND);
            }

            break;

        case AVAHI_BROWSER_REMOVE:
            assert(record);
            assert(record->key->type == AVAHI_DNS_TYPE_A || record->key->type == AVAHI_DNS_TYPE_AAAA);

            if (r->address_record && avahi_record_equal_no_ttl(record, r->address_record)) {
                avahi_record_unref(r->address_record);
                r->address_record = NULL;

                r->flags = flags;


                /** Look for a replacement */
                if (r->record_browser_aaaa)
                    avahi_s_record_browser_restart(r->record_browser_aaaa);
                if (r->record_browser_a)
                    avahi_s_record_browser_restart(r->record_browser_a);

                start_timeout(r);
            }

            break;

        case AVAHI_BROWSER_CACHE_EXHAUSTED:
        case AVAHI_BROWSER_ALL_FOR_NOW:
            /* Ignore */
            break;

        case AVAHI_BROWSER_FAILURE:

            /* Stop browsers */

            if (r->record_browser_aaaa)
                avahi_s_record_browser_free(r->record_browser_aaaa);
            if (r->record_browser_a)
                avahi_s_record_browser_free(r->record_browser_a);

            r->record_browser_a = r->record_browser_aaaa = NULL;
            r->flags = flags;

            finish(r, AVAHI_RESOLVER_FAILURE);
            break;
    }
}
#endif

AvahiSHostNameResolver *avahi_s_host_name_resolver_new(
    AvahiServer *server,
    AvahiIfIndex interface,
    AvahiProtocol protocol,
    const char *host_name,
    AvahiProtocol aprotocol,
    AvahiLookupFlags flags,
    AvahiSHostNameResolverCallback callback,
    void* userdata) {

    AvahiSHostNameResolver *r;
    AvahiKey *k;

    assert(server);
    assert(host_name);
    assert(callback);

    AVAHI_CHECK_VALIDITY_RETURN_NULL(server, AVAHI_IF_VALID(interface), AVAHI_ERR_INVALID_INTERFACE);
    AVAHI_CHECK_VALIDITY_RETURN_NULL(server, AVAHI_PROTO_VALID(protocol), AVAHI_ERR_INVALID_PROTOCOL);
    AVAHI_CHECK_VALIDITY_RETURN_NULL(server, avahi_is_valid_fqdn(host_name), AVAHI_ERR_INVALID_HOST_NAME);
    AVAHI_CHECK_VALIDITY_RETURN_NULL(server, AVAHI_PROTO_VALID(aprotocol), AVAHI_ERR_INVALID_PROTOCOL);
    AVAHI_CHECK_VALIDITY_RETURN_NULL(server, AVAHI_FLAGS_VALID(flags, AVAHI_LOOKUP_USE_WIDE_AREA|AVAHI_LOOKUP_USE_MULTICAST), AVAHI_ERR_INVALID_FLAGS);

    if (!(r = avahi_new(AvahiSHostNameResolver, 1))) {
        avahi_server_set_errno(server, AVAHI_ERR_NO_MEMORY);
        return NULL;
    }

    r->server = server;
    r->host_name = avahi_normalize_name_strdup(host_name);
    r->callback = callback;
    r->userdata = userdata;
    r->address_record = NULL;
    r->interface = interface;
    r->protocol = protocol;
    r->flags = 0;

    r->record_browser_a = r->record_browser_aaaa = NULL;

    r->time_event = NULL;

    AVAHI_LLIST_PREPEND(AvahiSHostNameResolver, resolver, server->host_name_resolvers, r);

    r->record_browser_aaaa = r->record_browser_a = NULL;

#ifdef HAVE_BONJOUR
    r->defer_time_event = NULL;
    r->watch_a = NULL;
    r->watch_a6 = NULL;
    r->client_a = NULL;
    r->client_a6 = NULL;
    r->lookup_flags = flags;
    avahi_resolve_host_name_start (r, aprotocol);
#else
    if (aprotocol == AVAHI_PROTO_INET || aprotocol == AVAHI_PROTO_UNSPEC) {
        k = avahi_key_new(host_name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_A);
        r->record_browser_a = avahi_s_record_browser_new(server, interface, protocol, k, flags, record_browser_callback, r);
        avahi_key_unref(k);

        if (!r->record_browser_a)
            goto fail;
    }

    if (aprotocol == AVAHI_PROTO_INET6 || aprotocol == AVAHI_PROTO_UNSPEC) {
        k = avahi_key_new(host_name, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_AAAA);
        r->record_browser_aaaa = avahi_s_record_browser_new(server, interface, protocol, k, flags, record_browser_callback, r);
        avahi_key_unref(k);

        if (!r->record_browser_aaaa)
            goto fail;
    }

    assert(r->record_browser_aaaa || r->record_browser_a);
#endif

    start_timeout(r);

    return r;

fail:
    avahi_s_host_name_resolver_free(r);
    return NULL;
}

void avahi_s_host_name_resolver_free(AvahiSHostNameResolver *r) {
    assert(r);

    AVAHI_LLIST_REMOVE(AvahiSHostNameResolver, resolver, r->server->host_name_resolvers, r);

    if (r->record_browser_a)
        avahi_s_record_browser_free(r->record_browser_a);

    if (r->record_browser_aaaa)
        avahi_s_record_browser_free(r->record_browser_aaaa);

    if (r->time_event)
        avahi_time_event_free(r->time_event);

    if (r->address_record)
        avahi_record_unref(r->address_record);
#ifdef HAVE_BONJOUR
    if (r->defer_time_event) {
        avahi_time_event_free(r->defer_time_event);
        r->defer_time_event = NULL;
    }

    if (r->watch_a)
       r->server->poll_api->watch_free(r->watch_a);
    if (r->watch_a6)
       r->server->poll_api->watch_free(r->watch_a6);

    if (r->client_a)
        DNSServiceRefDeallocate(r->client_a);
    if (r->client_a6)
        DNSServiceRefDeallocate(r->client_a6);
#endif

    avahi_free(r->host_name);
    avahi_free(r);
}
