DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (0ddcbf234291)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * 
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2001
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Dan Mosedale <dmose@netscape.com> (Original Author)
 *   Leif Hedstrom <leif@netscape.com>
 *   Simon Wilkinson <simon@sxw.org.uk>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. 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 MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "nsLDAPAutoCompleteSession.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIProxyObjectManager.h"
#include "nsILDAPURL.h"
#include "nsILDAPService.h"
#include "nspr.h"
#include "nsIStringBundle.h"
#include "nsCRTGlue.h"
#include "nsIObserverService.h"
#include "nsNetUtil.h"
#include "nsICategoryManager.h"
#include "nsCategoryManagerUtils.h"
#include "nsILDAPService.h"
#include "nsILDAPMessage.h"
#include "nsILDAPErrors.h"
#include "nsXPCOMCIDInternal.h"

#ifdef PR_LOGGING
static PRLogModuleInfo *sLDAPAutoCompleteLogModule = 0;
#endif


// Because this object gets called via proxies, we need to use a THREADSAFE
// ISUPPORTS; if bug 101252 gets fixed, we can go back to the non-threadsafe
// version.
//
NS_IMPL_THREADSAFE_ISUPPORTS3(nsLDAPAutoCompleteSession, 
                              nsIAutoCompleteSession, nsILDAPMessageListener,
                              nsILDAPAutoCompleteSession)

nsLDAPAutoCompleteSession::nsLDAPAutoCompleteSession() :
    mState(UNBOUND), 
    mFilterTemplate("(|(cn=%v1*%v2-*)(mail=%v1*%v2-*)(sn=%v1*%v2-*))"),
    mMaxHits(100), mMinStringLength(2), mCjkMinStringLength(0), 
    mSearchAttrs(0), mSearchAttrsSize(0), mVersion(nsILDAPConnection::VERSION3)
{
}

nsLDAPAutoCompleteSession::~nsLDAPAutoCompleteSession()
{
    if (mSearchAttrs) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mSearchAttrsSize, mSearchAttrs);
    }
    NS_IF_RELEASE(mConnection);
}

#define IS_CJK_CHAR_FOR_LDAP(u)  (0x2e80 <= (u) && (u) <= 0xd7ff)

/* void onStartLookup (in wstring searchString, in nsIAutoCompleteResults previousSearchResult, in nsIAutoCompleteListener listener); */
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::OnStartLookup(const PRUnichar *searchString, 
                                         nsIAutoCompleteResults *previousSearchResult,
                                         nsIAutoCompleteListener *listener)
{
    nsresult rv; // Hold return values from XPCOM calls

#ifdef PR_LOGGING
    // Initialize logging, if it hasn't been already.
    if (!sLDAPAutoCompleteLogModule) {
        sLDAPAutoCompleteLogModule = PR_NewLogModule("ldapautocomplete");

        NS_ABORT_IF_FALSE(sLDAPAutoCompleteLogModule, 
                          "failed to initialize ldapautocomplete log module");
    }
#endif

    PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
           ("nsLDAPAutoCompleteSession::OnStartLookup entered\n"));
    
    if (!listener) {
        NS_ERROR("nsLDAPAutoCompleteSession::OnStartLookup(): NULL listener"
                 "passed in");
        return NS_ERROR_NULL_POINTER;
    } else {
        mListener = listener;   // Save it for later callbacks
    }

    // Ignore the empty string, strings with @ in them, and strings
    // that are too short.
    if (searchString[0] == 0 ||
        nsDependentString(searchString).FindChar(PRUnichar('@'), 0) != -1 || 
        nsDependentString(searchString).FindChar(PRUnichar(','), 0) != -1 || 
        ( !IS_CJK_CHAR_FOR_LDAP(searchString[0]) ?
          mMinStringLength && NS_strlen(searchString) < mMinStringLength :
          mCjkMinStringLength && NS_strlen(searchString) < 
          mCjkMinStringLength ) ) {

        FinishAutoCompleteLookup(nsIAutoCompleteStatus::ignored, 0, mState);
        return NS_OK;
    } else {
        mSearchString = searchString;        // save it for later use
    }

    // Make sure this was called appropriately.
    if (mState == SEARCHING || mState == BINDING) {
        NS_ERROR("nsLDAPAutoCompleteSession::OnStartLookup(): called while "
                 "search already in progress; no lookup started.");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems,
                                 NS_ERROR_FAILURE, mState);
        return NS_ERROR_FAILURE;
    }

    NS_ASSERTION(mFormatter, "nsLDAPAutoCompleteSession::OnStartLookup(): "
                 "formatter attribute has not been set");

    // See if this is a narrow search that we could potentially do locally.
    if (previousSearchResult) {

        // Get the string representing previous search results.
        nsString prevSearchStr;

        rv = previousSearchResult->GetSearchString(
            getter_Copies(prevSearchStr));
        if ( NS_FAILED(rv) ) {
            NS_ERROR("nsLDAPAutoCompleteSession::OnStartLookup(): couldn't "
                     "get search string from previousSearchResult");
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, 
                                     NS_ERROR_FAILURE, mState);
            return NS_ERROR_FAILURE;
        }

        // Does the string actually contain anything?
        if ( prevSearchStr.get() && prevSearchStr.get()[0]) {

            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::OnStartLookup(): starting "
                    "narrowing search\n"));

            // XXXdmose for performance, we should really do a local,
            // synchronous search against the existing dataset instead of
            // just kicking off a new LDAP search here.  When implementing
            // this, need to be sure that only previous results which did not
            // hit the size limit and were successfully completed are used.
            //
            mState = SEARCHING;
            return DoTask();
        }
    }

    // Init connection if necessary
    //
    switch (mState) {
    case UNBOUND:

        // Initialize the connection.  
        //
        rv = InitConnection();
        if (NS_FAILED(rv)) {

            // InitConnection() will have already called
            // FinishAutoCompleteLookup for us as necessary
            //
            return rv;
        }

        return NS_OK;

    case BOUND:

        PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
               ("nsLDAPAutoComplete::OnStartLookup(): subsequent search "
                "starting"));

        // Kick off an LDAP search
        mState = SEARCHING;
        return DoTask();

    case INITIALIZING:
        // We don't need to do anything here (for now at least), because
        // we can't really abandon the initialization. If we allowed the
        // initialization to be aborted, we could potentially lock the
        // UI thread again, since the DNS service might be stalled.
        //
        return NS_OK;

    case BINDING:
    case SEARCHING:
        // We should never get here
        NS_ERROR("nsLDAPAutoCompleteSession::OnStartLookup(): unexpected "
                 "value of mStatus");
        return NS_ERROR_UNEXPECTED;
    }
    
    return NS_ERROR_UNEXPECTED;     /*NOTREACHED*/
}

/* void onStopLookup (); */
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::OnStopLookup()
{
#ifdef PR_LOGGING
    // Initialize logging, if it hasn't been already.
    if (!sLDAPAutoCompleteLogModule) {
        sLDAPAutoCompleteLogModule = PR_NewLogModule("ldapautocomplete");

        NS_ABORT_IF_FALSE(sLDAPAutoCompleteLogModule, 
                          "failed to initialize ldapautocomplete log module");
    }
#endif

    PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
           ("nsLDAPAutoCompleteSession::OnStopLookup entered\n"));

    switch (mState) {
    case UNBOUND:
        // Nothing to stop
        return NS_OK;

    case BOUND:
        // Nothing to stop
        return NS_OK;

    case INITIALIZING:
        // We can't or shouldn't abort the initialization, because then the
        // DNS service can hang again...
        //
        return NS_OK;

    case BINDING:
    case SEARCHING:
        // Abandon the operation, if there is one
        if (mOperation) {
            nsresult rv = mOperation->AbandonExt();

            if (NS_FAILED(rv)) {
                // Since there's nothing interesting that can or should be
                // done if this abandon failed, warn about it and move on
                NS_WARNING("nsLDAPAutoCompleteSession::OnStopLookup(): "
                           "error calling mOperation->AbandonExt()");
            }

            // Force nsCOMPtr to release mOperation
            mOperation = 0;
        }

        // Set the status properly, set to UNBOUND of we were binding, or
        // to BOUND if we were searching.
        mState = (mState == BINDING ? UNBOUND : BOUND);
        if (mState == UNBOUND)
          NS_IF_RELEASE(mConnection);
    }

    mResultsArray = 0;
    mResults = 0;
    mListener = 0;

    return NS_OK;
}

/* void onAutoComplete (in wstring searchString, in nsIAutoCompleteResults previousSearchResult, in nsIAutoCompleteListener listener); */
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::OnAutoComplete(const PRUnichar *searchString, 
                                 nsIAutoCompleteResults *previousSearchResult, 
                                          nsIAutoCompleteListener *listener)
{
    // OnStopLookup should have already been called, so there's nothing to
    // free here.  Additionally, as of this writing, no one is hanging around
    // waiting for mListener->OnAutoComplete() to be called either, and if
    // they were, it's unclear what we'd return, since we're not guaranteed
    // to be in any particular state.  My suspicion is that this method
    // (nsIAutoCompleteSession::OnAutoComplete) should probably be removed
    // from the interface.

    return NS_OK;
}

/**
 * Messages received are passed back via this function.
 *
 * @arg aMessage  The message that was returned, NULL if none was.
 *
 * void OnLDAPMessage (in nsILDAPMessage aMessage)
 */
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::OnLDAPMessage(nsILDAPMessage *aMessage)
{
    PRInt32 messageType;

    // Just in case.
    // XXXdmose the semantics of NULL are currently undefined, but are likely
    // to be defined once we insert timeout handling code into the XPCOM SDK
    // At that time we should figure out if this still the right thing to do.
    if (!aMessage) {
        return NS_OK;
    }

    // Figure out what sort of message was returned.
    nsresult rv = aMessage->GetType(&messageType);
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::OnLDAPMessage(): unexpected "
                 "error in aMessage->GetType()");
       
        // Don't call FinishAutoCompleteLookup(), as this could conceivably 
        // be an anomaly, and perhaps the next message will be ok. If this
        // really was a problem, this search should eventually get
        // reaped by a timeout (once that code gets implemented).
        return NS_ERROR_UNEXPECTED;
    }

    // If this message is not associated with the current operation,
    // discard it, since it is probably from a previous (aborted)
    // operation.
    PRBool isCurrent;
    rv = IsMessageCurrent(aMessage, &isCurrent);
    if (NS_FAILED(rv)) {
        // IsMessageCurrent will have logged any necessary errors
        return rv;
    }
    if ( ! isCurrent ) {
        PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG,
               ("nsLDAPAutoCompleteSession::OnLDAPMessage(): received message "
                "from operation other than current one; discarded"));
        return NS_OK;
    }

    // XXXdmose - we may want a small state machine either here or
    // or in the nsLDAPConnection object, to make sure that things are
    // happening in the right order and timing out appropriately. This will
    // certainly depend on how timeouts are implemented, and how binding
    // gets is dealt with by nsILDAPService. Also need to deal with the case
    // where a bind callback happens after onStopLookup was called.
    switch (messageType) {

    case nsILDAPMessage::RES_BIND:

        // A bind has completed
        if (mState != BINDING) {
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::OnLDAPMessage(): LDAP bind "
                    "entry returned after OnStopLookup() called; ignoring"));

            // XXXdmose when nsLDAPService integration happens, need to make
            // sure that the possibility of having an already bound
            // connection, due to a previously unaborted bind, doesn't cause
            // any problems.

            return NS_OK;
        }

        rv = OnLDAPMessageBind(aMessage);
        if (NS_FAILED(rv)) {
          mState = UNBOUND;
          FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, 
                                   rv, UNBOUND);
        }
        else
          mState = SEARCHING;

        return rv;

    case nsILDAPMessage::RES_SEARCH_ENTRY:
        
        // Ignore this if OnStopLookup was already called.
        if (mState != SEARCHING) {
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::OnLDAPMessage(): LDAP search "
                    "entry returned after OnStopLoookup() called; ignoring"));
            return NS_OK;
        }

        // A search entry has been returned.
        return OnLDAPSearchEntry(aMessage);

    case nsILDAPMessage::RES_SEARCH_RESULT:

        // Ignore this if OnStopLookup was already called.
        if (mState != SEARCHING) {
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG,
                   ("nsLDAPAutoCompleteSession::OnLDAPMessage(): LDAP search "
                    "result returned after OnStopLookup called; ignoring"));
            return NS_OK;
        }

        // The search is finished; we're all done.
        return OnLDAPSearchResult(aMessage);

    default:
        
        // Given the LDAP operations nsLDAPAutoCompleteSession uses, we should
        // never get here. If we do get here in a release build, it's
        // probably a bug, but maybe it's the LDAP server doing something
        // weird. Might as well try and continue anyway. The session should
        // eventually get reaped by the timeout code, if necessary.
        //
        NS_ERROR("nsLDAPAutoCompleteSession::OnLDAPMessage(): unexpected "
                 "LDAP message received");
        return NS_OK;
    }
}

void
nsLDAPAutoCompleteSession::InitFailed(PRBool aCancelled)
{
  FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, 0,
                           UNBOUND);
}

// void onLDAPInit (in nsresult aStatus);
NS_IMETHODIMP
nsLDAPAutoCompleteSession::OnLDAPInit(nsILDAPConnection *aConn, nsresult aStatus)
{
  nsresult rv = nsAbLDAPListenerBase::OnLDAPInit(aConn, aStatus);

  if (NS_SUCCEEDED(rv))
    mState = BINDING;

  return rv;
}

nsresult
nsLDAPAutoCompleteSession::OnLDAPSearchEntry(nsILDAPMessage *aMessage)
{
    PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
           ("nsLDAPAutoCompleteSession::OnLDAPSearchEntry entered\n"));

    // Make sure this is only getting called after DoTask has
    // initialized the result set.
    NS_ASSERTION(mResultsArray,
                 "nsLDAPAutoCompleteSession::OnLDAPSearchEntry(): "
                 "mResultsArrayItems is uninitialized");

    // Errors in this method return an error (which ultimately gets
    // ignored, since this is being called through an async proxy).
    // But the important thing is that we're bailing out here rather
    // than trying to generate a bogus nsIAutoCompleteItem. Also note
    // that FinishAutoCompleteLookup is _NOT_ being called here, because
    // this error may just have to do with this particular item.

    // Generate an autocomplete item from this message by calling the
    // formatter.
    nsCOMPtr<nsIAutoCompleteItem> item;
    nsresult rv = mFormatter->Format(aMessage, getter_AddRefs(item));
    if (NS_FAILED(rv)) {
        PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG,
               ("nsLDAPAutoCompleteSession::OnLDAPSearchEntry(): "
                "mFormatter->Format() failed"));
        return NS_ERROR_FAILURE;
    }

    rv = mResultsArray->AppendElement(item);
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::OnLDAPSearchEntry(): "
                 "mItems->AppendElement() failed");
        return NS_ERROR_FAILURE;
    }

    // Remember that something has been returned.
    mEntriesReturned++;

    return NS_OK;
}

nsresult
nsLDAPAutoCompleteSession::OnLDAPSearchResult(nsILDAPMessage *aMessage)
{
    nsresult rv;        // Temp for return vals

    PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
           ("nsLDAPAutoCompleteSession::OnLDAPSearchResult entered\n"));

    // Figure out if we succeeded or failed, and set the status
    // and default index appropriately.
    AutoCompleteStatus status;
    PRInt32 lderrno;

    if (mEntriesReturned) {

        status = nsIAutoCompleteStatus::matchFound;

        // There's at least one match, so the default index should
        // point to the first thing here.  This ensures that if the local
        // addressbook autocomplete session only found foo@local.domain,
        // this will be given preference.
        rv = mResults->SetDefaultItemIndex(0);
        if (NS_FAILED(rv)) {
            NS_ERROR("nsLDAPAutoCompleteSession::OnLDAPSearchResult(): "
                     "mResults->SetDefaultItemIndex(0) failed");
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
        }
    } else {
        // Note that we only look at the error code if there are no results for
        // this session; if we got results and then an error happened, this
        // is ignored, in part because it seems likely to be confusing to the
        // user, and in part because it is likely to be scrolled out of view
        // anyway.
        aMessage->GetErrorCode(&lderrno);
        if (lderrno != nsILDAPErrors::SUCCESS) {

            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::OnLDAPSearchResult(): "
                    "lderrno=%d\n", lderrno));
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, 
                                     NS_ERROR_GENERATE_FAILURE(
                                         NS_ERROR_MODULE_LDAP, lderrno), 
                                     BOUND);
            return NS_OK;
        }

        // We could potentially keep track of non-fatal errors to the
        // search, and if there has been more than 1, and there are no entries,
        // we could return |failed| instead of |noMatch|. It's unclear to me
        // that this actually buys us anything though.
        status = nsIAutoCompleteStatus::noMatch;
    }

    // Call the mListener's OnAutoComplete and clean up
    //
    // XXXdmose should we really leave the connection BOUND here?
    FinishAutoCompleteLookup(status, NS_OK, BOUND);

    return NS_OK;
}

nsresult
nsLDAPAutoCompleteSession::DoTask()
{
    nsresult rv; // temp for xpcom return values
    nsCOMPtr<nsILDAPMessageListener> selfProxy; // for callback

    PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
           ("nsLDAPAutoCompleteSession::DoTask entered\n"));

    // Create and initialize an LDAP operation (to be used for the search).
    mOperation = 
        do_CreateInstance("@mozilla.org/network/ldap-operation;1", &rv);

    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): couldn't "
                 "create @mozilla.org/network/ldap-operation;1");

        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 BOUND);
        return NS_ERROR_FAILURE;
    }

    // Get a proxy object so the callback happens on the main thread.
    nsCOMPtr<nsIProxyObjectManager> proxyObjMgr = do_GetService(NS_XPCOMPROXY_CONTRACTID, &rv);
    if (NS_FAILED(rv)) {
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, UNBOUND);
        return NS_ERROR_FAILURE;
    }
    rv = proxyObjMgr->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                              NS_GET_IID(nsILDAPMessageListener), 
                              static_cast<nsILDAPMessageListener *>(this), 
                              NS_PROXY_ASYNC | NS_PROXY_ALWAYS, 
                              getter_AddRefs(selfProxy));
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): couldn't "
                 "create proxy to this object for callback");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 BOUND);
        return NS_ERROR_FAILURE;
    }

    // Initialize the LDAP operation object.
    rv = mOperation->Init(mConnection, selfProxy, nsnull);
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): couldn't "
                 "initialize LDAP operation");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 BOUND);
        return NS_ERROR_UNEXPECTED;
    }

    // Set the server and client controls on the operation.
    if (mSearchServerControls) {
        rv = mOperation->SetServerControls(mSearchServerControls);
        if (NS_FAILED(rv)) {
            NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): couldn't "
                     "initialize LDAP search operation server controls");
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_ERROR_UNEXPECTED;
        }
    }
    if (mSearchClientControls) {
        rv = mOperation->SetClientControls(mSearchClientControls);
        if (NS_FAILED(rv)) {
            NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): couldn't "
                     "initialize LDAP search operation client controls");
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_ERROR_UNEXPECTED;
        }
    }

    // Get the search filter associated with the directory server url;
    // it will be ANDed with the rest of the search filter that we're using.
    nsCAutoString urlFilter;
    rv = mDirectoryUrl->GetFilter(urlFilter);
    if ( NS_FAILED(rv) ){
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv,
                                 BOUND);
        return NS_ERROR_UNEXPECTED;
    }

    // Get the LDAP service, since createFilter is called through it.
    nsCOMPtr<nsILDAPService> ldapSvc = do_GetService(
        "@mozilla.org/network/ldap-service;1", &rv);
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): couldn't "
                 "get @mozilla.org/network/ldap-service;1");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv,
                                 BOUND);
        return NS_ERROR_FAILURE;
    }

    // If urlFilter is unset (or set to the default "objectclass=*"), there's
    // no need to AND in an empty search term, so leave prefix and suffix empty.
    nsCAutoString prefix, suffix;
    if (urlFilter.Length() && !urlFilter.Equals(NS_LITERAL_CSTRING("(objectclass=*)"))) {

        // If urlFilter isn't parenthesized, we need to add in parens so that
        // the filter works as a term to &
        if (urlFilter[0] != '(') {
            prefix.AssignLiteral("(&(");
            prefix.Append(urlFilter);
            prefix.AppendLiteral(")");
        } else {
            prefix.AssignLiteral("(&");
            prefix.Append(urlFilter);
        }
        
        suffix = ')';
    }

    // Generate an LDAP search filter from mFilterTemplate. If it's unset,
    // use the default.
#define MAX_AUTOCOMPLETE_FILTER_SIZE 1024
    nsCAutoString searchFilter;
    rv = ldapSvc->CreateFilter(MAX_AUTOCOMPLETE_FILTER_SIZE,
                               mFilterTemplate,
                               prefix, suffix, EmptyCString(), 
                               NS_ConvertUTF16toUTF8(mSearchString),
                               searchFilter);
    if (NS_FAILED(rv)) {
        switch(rv) {

        case NS_ERROR_OUT_OF_MEMORY:
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv,
                                     BOUND);
            return rv;

        case NS_ERROR_NOT_AVAILABLE:
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::DoTask(): "
                    "createFilter generated filter longer than max filter "
                    "size of %d", MAX_AUTOCOMPLETE_FILTER_SIZE));
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv,
                                     BOUND);
            return rv;

        case NS_ERROR_INVALID_ARG:
        case NS_ERROR_UNEXPECTED:
        default:

            // All this stuff indicates code bugs.
            NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): "
                     "createFilter returned unexpected value");
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_ERROR_UNEXPECTED;
        }

    }

    // If the results array for this search hasn't already been created, do
    // so now. Note that we don't return ::failureItems here, because if
    // there's no array, there's nowhere to put the items.
    rv = CreateResultsArray();
    if (NS_FAILED(rv)) {
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failed, rv, BOUND);
    }

    // Nothing returned yet!
    mEntriesReturned = 0;
    
    // Get the base dn to search
    nsCAutoString dn;
    rv = mDirectoryUrl->GetDn(dn);
    if ( NS_FAILED(rv) ){
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv,
                                 BOUND);
        return NS_ERROR_UNEXPECTED;
    }

    // And the scope
    PRInt32 scope;
    rv = mDirectoryUrl->GetScope(&scope);
    if ( NS_FAILED(rv) ){
        mState = BOUND;
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 BOUND);
        return NS_ERROR_UNEXPECTED;
    }

    // Take the relevant controls on this object and set them
    // on the operation
    rv = mOperation->SetServerControls(mSearchServerControls.get());
    if ( NS_FAILED(rv) ){
        mState = BOUND;
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 BOUND);
        return NS_ERROR_UNEXPECTED;
    }

    rv = mOperation->SetClientControls(mSearchClientControls.get());
    if ( NS_FAILED(rv) ){
        mState = BOUND;
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 BOUND);
        return NS_ERROR_UNEXPECTED;
    }

    // Time to kick off the search.
    //
    // XXXdmose what about timeouts? 
    //
    rv = mOperation->SearchExt(dn, scope, searchFilter, mSearchAttrsSize,
                               const_cast<const char **>(mSearchAttrs),
                               0, mMaxHits);
    if (NS_FAILED(rv)) {
        switch(rv) {

        case NS_ERROR_LDAP_ENCODING_ERROR:
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::DoTask(): SearchExt "
                    "returned NS_ERROR_LDAP_ENCODING_ERROR"));
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_OK;

        case NS_ERROR_LDAP_FILTER_ERROR:
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::DoTask(): SearchExt "
                    "returned NS_ERROR_LDAP_FILTER_ERROR"));
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_OK;

        case NS_ERROR_LDAP_SERVER_DOWN:
            // XXXdmose discuss with leif how to handle this in general in the
            // LDAP XPCOM SDK.

            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::DoTask(): SearchExt "
                    "returned NS_ERROR_LDAP_SERVER_DOWN"));
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv,
                                     UNBOUND);
            return NS_OK;

        case NS_ERROR_OUT_OF_MEMORY:
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_ERROR_OUT_OF_MEMORY;

        case NS_ERROR_LDAP_NOT_SUPPORTED:
        case NS_ERROR_NOT_INITIALIZED:        
        case NS_ERROR_INVALID_ARG:
        default:

            // All this stuff indicates code bugs.
            NS_ERROR("nsLDAPAutoCompleteSession::DoTask(): SearchExt "
                     "returned unexpected value");
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     BOUND);
            return NS_ERROR_UNEXPECTED;
        }
    }

    return NS_OK;
}

// XXXdmose - stopgap routine until nsLDAPService is working
//
nsresult
nsLDAPAutoCompleteSession::InitConnection()
{
    nsresult rv;        // temp for xpcom return values
    nsCOMPtr<nsILDAPMessageListener> selfProxy;
    
    NS_ASSERTION(!mConnection, "in InitConnection w/ existing connection");

    // Create an LDAP connection
    nsCOMPtr<nsILDAPConnection> connection =
      do_CreateInstance("@mozilla.org/network/ldap-connection;1", &rv);
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::InitConnection(): could "
                 "not create @mozilla.org/network/ldap-connection;1");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 UNBOUND);
        return NS_ERROR_FAILURE;
    }

    NS_ADDREF(mConnection = connection);

    // Have we been properly initialized?
    if (!mDirectoryUrl) {
        NS_ERROR("nsLDAPAutoCompleteSession::InitConnection(): mDirectoryUrl "
                 "is NULL");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 UNBOUND);
        return NS_ERROR_NOT_INITIALIZED;
    }

    // Get a proxy object so the callback happens on the main thread.
    nsCOMPtr<nsIProxyObjectManager> proxyObjMgr = do_GetService(NS_XPCOMPROXY_CONTRACTID, &rv);
    if (NS_FAILED(rv)) {
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, UNBOUND);
        return NS_ERROR_FAILURE;
    }
    rv = proxyObjMgr->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, 
                              NS_GET_IID(nsILDAPMessageListener), 
                              static_cast<nsILDAPMessageListener *>(this), 
                              NS_PROXY_ASYNC | NS_PROXY_ALWAYS, 
                              getter_AddRefs(selfProxy));
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::InitConnection(): couldn't "
                 "create proxy to this object for callback");
        FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                 UNBOUND);
        return NS_ERROR_FAILURE;
    }

    // Initialize the connection. This will cause an asynchronous DNS
    // lookup to occur, and we'll finish the binding of the connection
    // in the OnLDAPInit() listener function.
    rv = mConnection->Init(mDirectoryUrl, mLogin, selfProxy, nsnull, mVersion);
    if (NS_FAILED(rv)) {
        switch (rv) {

        case NS_ERROR_OUT_OF_MEMORY:
        case NS_ERROR_NOT_AVAILABLE:
        case NS_ERROR_FAILURE:
            PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
                   ("nsLDAPAutoCompleteSession::InitConnection(): mSimpleBind "
                    "failed, rv = 0x%lx", rv));
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     UNBOUND);
            return rv;

        case NS_ERROR_ILLEGAL_VALUE:
        default:
            FinishAutoCompleteLookup(nsIAutoCompleteStatus::failureItems, rv, 
                                     UNBOUND);
            return NS_ERROR_UNEXPECTED;
        }
    }

    // Set our state
    mState = INITIALIZING;

    return NS_OK;
}

nsresult
nsLDAPAutoCompleteSession::CreateResultsArray(void)
{
    nsresult rv;

    // Create a result set
    mResults = do_CreateInstance(NS_AUTOCOMPLETERESULTS_CONTRACTID, &rv);

    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::DoTask() couldn't"
                 " create " NS_AUTOCOMPLETERESULTS_CONTRACTID);
        return NS_ERROR_FAILURE;
    }

    // This seems to be necessary for things to work, though I'm not sure
    // why that's true.
    rv = mResults->SetSearchString(mSearchString.get());
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::OnLDAPSearchResult(): couldn't "
                 "set search string in results object");
        return NS_ERROR_FAILURE;
    }

    // Get a pointer to the array in question now, so that we don't have to
    // keep re-fetching it every time an entry callback happens.
    rv = mResults->GetItems(getter_AddRefs(mResultsArray));
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::DoTask() couldn't "
                 "get results array.");
        return NS_ERROR_FAILURE;
    }

    return NS_OK;
}

void
nsLDAPAutoCompleteSession::FinishAutoCompleteLookup(
    AutoCompleteStatus aACStatus, const nsresult aResult,
    enum SessionState aEndState)
{
    nsCOMPtr<nsIAutoCompleteItem> errorItem; // pointer to item we may create
    nsresult rv; // temp for return value 

    // If there's a listener, inform the listener that the search is over.
    rv = NS_OK;
    if (mListener) {
        
        switch (aACStatus) {

        case nsIAutoCompleteStatus::matchFound:
            rv = mListener->OnAutoComplete(mResults, aACStatus);
            break;

        case nsIAutoCompleteStatus::failureItems:
            // If the results array hasn't already been created, make one
            // to return the error message.  If there's an error, fallback
            // to ::failed
            if (!mResults) {
                rv = CreateResultsArray();
                if (NS_FAILED(rv)) {
                    NS_ERROR("nsLDAPAutoCompleteSession::"
                             "FinishAutoCompleteLookup():"
                             " CreateResultsArray() failed");
                    rv = mListener->OnAutoComplete(0, 
                                                nsIAutoCompleteStatus::failed);
                    break;
                }
            }

            // Create the error item.
            rv = mFormatter->FormatException(mState, aResult,
                                             getter_AddRefs(errorItem));
            if (NS_SUCCEEDED(rv)) {

                // Try and append the error item; falling back to ::failed
                // if there's a problem.
                //
                rv = mResultsArray->AppendElement(errorItem);
                if (NS_FAILED(rv)) {
                    NS_ERROR("nsLDAPAutoCompleteSession::"
                             "FinishAutoCompleteLookup():"
                             " mItems->AppendElement() failed");
                    rv = mListener->OnAutoComplete(0, 
                                                nsIAutoCompleteStatus::failed);
                    break;
                } 

                // We don't want the autocomplete widget trying to
                // automagically use the error item for anything. If
                // something goes wrong here, continue on anyway.
                //
                (void)mResults->SetDefaultItemIndex(-1);

                rv = mListener->OnAutoComplete(mResults, 
                                          nsIAutoCompleteStatus::failureItems);
                break;
            } 

            // Fallback to ::failed
            NS_ERROR("nsLDAPAutoCompleteSession::FinishAutoCompleteLookup(): "
                     "error calling FormatException()");

            rv = mListener->OnAutoComplete(0, nsIAutoCompleteStatus::failed);
            break;
        
        case nsIAutoCompleteStatus::failed:
        default:
            rv = mListener->OnAutoComplete(0, aACStatus);
            break;
        }

    } else {
        // If there's no listener, something's wrong.
        NS_ERROR("nsLDAPAutoCompleteSession::FinishAutoCompleteLookup(): "
                 "called with mListener unset!");
    }

    if (NS_FAILED(rv)) {

        // There's nothing we can actually do here other than warn.
        NS_WARNING("nsLDAPAutoCompleteSession::FinishAutoCompleteLookup(): "
                   "error calling mListener->OnAutoComplete()");
    }

    // Set the state appropriately.
    mState = aEndState;

    // We're done with various things; cause nsCOMPtr to release them.
    mResultsArray = 0;
    mResults = 0;
    mListener = 0;
    mOperation = 0;

    // If we are unbound, drop the connection (if any).
    if (mState == UNBOUND) {
        NS_IF_RELEASE(mConnection);
    }
}

// methods for nsILDAPAutoCompleteSession

// attribute AUTF8String searchFilter;
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::GetFilterTemplate(nsACString & aFilterTemplate)
{
    aFilterTemplate.Assign(mFilterTemplate);

    return NS_OK;
}
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::SetFilterTemplate(const nsACString & aFilterTemplate)
{
    mFilterTemplate.Assign(aFilterTemplate);

    return NS_OK;
}


// attribute long maxHits;
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::GetMaxHits(PRInt32 *aMaxHits)
{
    if (!aMaxHits) {
        return NS_ERROR_NULL_POINTER;
    }

    *aMaxHits = mMaxHits;
    return NS_OK;
}
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::SetMaxHits(PRInt32 aMaxHits)
{
    if ( aMaxHits < -1 || aMaxHits > 65535) {
        return NS_ERROR_ILLEGAL_VALUE;
    }

    mMaxHits = aMaxHits;
    return NS_OK;
}

// attribute nsILDAPURL serverURL; 
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::GetServerURL(nsILDAPURL * *aServerURL)
{
    if (! aServerURL ) {
        return NS_ERROR_NULL_POINTER;
    }
    
    NS_IF_ADDREF(*aServerURL = mDirectoryUrl);

    return NS_OK;
}
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::SetServerURL(nsILDAPURL * aServerURL)
{
    if (! aServerURL ) {
        return NS_ERROR_NULL_POINTER;
    }

    mDirectoryUrl = aServerURL;

    // The following line will cause the next call to OnStartLookup to
    // call InitConnection again. This will reinitialize all the relevant
    // member variables and kick off an LDAP bind. By virtue of the magic of
    // nsCOMPtrs, doing this will cause all the nsISupports-based stuff to
    // be Released, which will eventually result in the old connection being
    // destroyed, and the destructor for that calls ldap_unbind()
    mState = UNBOUND;

    return NS_OK;
}

// attribute unsigned long minStringLength
NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetMinStringLength(PRUint32 *aMinStringLength)
{
    if (!aMinStringLength) {
        return NS_ERROR_NULL_POINTER;
    }

    *aMinStringLength = mMinStringLength;
    return NS_OK;
}
NS_IMETHODIMP
nsLDAPAutoCompleteSession::SetMinStringLength(PRUint32 aMinStringLength)
{
    mMinStringLength = aMinStringLength;

    return NS_OK;
}

// attribute unsigned long cjkMinStringLength
NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetCjkMinStringLength(PRUint32 *aCjkMinStringLength)
{
    if (!aCjkMinStringLength) {
        return NS_ERROR_NULL_POINTER;
    }

    *aCjkMinStringLength = mCjkMinStringLength;
    return NS_OK;
}
NS_IMETHODIMP
nsLDAPAutoCompleteSession::SetCjkMinStringLength(PRUint32 aCjkMinStringLength)
{
    mCjkMinStringLength = aCjkMinStringLength;

    return NS_OK;
}

// Check to see if the message returned is related to our current operation
// if there is no current operation, it's not. :-)
nsresult 
nsLDAPAutoCompleteSession::IsMessageCurrent(nsILDAPMessage *aMessage, 
                                            PRBool *aIsCurrent)
{
    // If there's no operation, this message must be stale (ie non-current).
    if ( !mOperation ) {
        *aIsCurrent = PR_FALSE;
        return NS_OK;
    }

    // Get the message id from the current operation.
    PRInt32 currentId;
    nsresult rv = mOperation->GetMessageID(&currentId);
    if (NS_FAILED(rv)) {
        PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
               ("nsLDAPAutoCompleteSession::IsMessageCurrent(): unexpected "
                "error 0x%lx calling mOperation->GetMessageId()", rv));
        return NS_ERROR_UNEXPECTED;
    }

    // Get the message operation from the message.
    nsCOMPtr<nsILDAPOperation> msgOp;
    rv = aMessage->GetOperation(getter_AddRefs(msgOp));
    if (NS_FAILED(rv)) {
        PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
               ("nsLDAPAutoCompleteSession::IsMessageCurrent(): unexpected "
                "error 0x%lx calling aMessage->GetOperation()", rv));
        return NS_ERROR_UNEXPECTED;
    }

    // Get the message operation id from the message operation.
    PRInt32 msgOpId;
    rv = msgOp->GetMessageID(&msgOpId);
    if (NS_FAILED(rv)) {
        PR_LOG(sLDAPAutoCompleteLogModule, PR_LOG_DEBUG, 
               ("nsLDAPAutoCompleteSession::IsMessageCurrent(): unexpected "
                "error 0x%lx calling msgOp->GetMessageId()", rv));
        return NS_ERROR_UNEXPECTED;
    }
    
    *aIsCurrent = (msgOpId == currentId);

    return NS_OK;
}

// attribute nsILDAPAutoCompFormatter formatter
NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetFormatter(nsILDAPAutoCompFormatter* *aFormatter)
{
    if (! aFormatter ) {
        return NS_ERROR_NULL_POINTER;
    }
    
    NS_IF_ADDREF(*aFormatter = mFormatter);

    return NS_OK;
}
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::SetFormatter(nsILDAPAutoCompFormatter* aFormatter)
{
    if (! aFormatter ) {
        return NS_ERROR_NULL_POINTER;
    }

    NS_ASSERTION(mState == UNBOUND || mState == BOUND, 
                 "nsLDAPAutoCompleteSession::SetFormatter was called when "
                 "mState was set to something other than BOUND or UNBOUND");

    mFormatter = aFormatter;

    // Ensure any old data is freed if necessary.
    if (mSearchAttrs) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mSearchAttrsSize, mSearchAttrs);
        mSearchAttrs = nsnull;
    }

    // Get and cache the attributes that will be used to do lookups.
    nsresult rv = mFormatter->GetAttributes(&mSearchAttrsSize, &mSearchAttrs);
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPAutoCompleteSession::SetFormatter(): "
                 " mFormatter->GetAttributes failed");
        return NS_ERROR_FAILURE;
    }
    
    return NS_OK;
}

NS_IMETHODIMP
nsLDAPAutoCompleteSession::SetLogin(const nsACString & aLogin)
{
    mLogin = aLogin;
    return NS_OK;
}
NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetLogin(nsACString & aLogin) 
{
    aLogin = mLogin;
    return NS_OK;
}

// attribute ACString saslMechanism

NS_IMETHODIMP
nsLDAPAutoCompleteSession::SetSaslMechanism(const nsACString & aSaslMechanism)
{
    mSaslMechanism.Assign(aSaslMechanism);
    return NS_OK;
}
NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetSaslMechanism(nsACString & aSaslMechanism)
{
    aSaslMechanism.Assign(mSaslMechanism);
    return NS_OK;
}

// attribute unsigned long version;
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::GetVersion(PRUint32 *aVersion)
{
    if (!aVersion) {
        return NS_ERROR_NULL_POINTER;
    }

    *aVersion = mVersion;
    return NS_OK;
}
NS_IMETHODIMP 
nsLDAPAutoCompleteSession::SetVersion(PRUint32 aVersion)
{
    if ( mVersion != nsILDAPConnection::VERSION2 && 
         mVersion != nsILDAPConnection::VERSION3) {
        return NS_ERROR_ILLEGAL_VALUE;
    }

    mVersion = aVersion;
    return NS_OK;
}

NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetSearchServerControls(nsIMutableArray **aControls)
{
    NS_IF_ADDREF(*aControls = mSearchServerControls);
    return NS_OK;
}

NS_IMETHODIMP
nsLDAPAutoCompleteSession::SetSearchServerControls(nsIMutableArray *aControls)
{
    mSearchServerControls = aControls;
    return NS_OK;
}

NS_IMETHODIMP
nsLDAPAutoCompleteSession::GetSearchClientControls(nsIMutableArray **aControls)
{
    NS_IF_ADDREF(*aControls = mSearchClientControls);
    return NS_OK;
}

NS_IMETHODIMP 
nsLDAPAutoCompleteSession::SetSearchClientControls(nsIMutableArray *aControls)
{
    mSearchClientControls = aControls;
    return NS_OK;
}