Power System Platform  2018w15a
Public Types | Public Member Functions | Protected Attributes | List of all members
Sum Class Reference

Sum the all inputs (can choose the input signal). More...

#include <Sum.h>

Inheritance diagram for Sum:
Inheritance graph
[legend]
Collaboration diagram for Sum:
Collaboration graph
[legend]

Public Types

enum  Signal { SIGNAL_POSITIVE = 0, SIGNAL_NEGATIVE }
 

Public Member Functions

 Sum (int id)
 
virtual void Draw (wxPoint2DDouble translation, double scale) const
 Draw the element. More...
 
virtual bool Contains (wxPoint2DDouble position) const
 Checks if the element contains a position. More...
 
virtual bool Intersects (wxRect2DDouble rect) const
 Check if the element's rect intersects other rect. More...
 
virtual bool ShowForm (wxWindow *parent, Element *element)
 Show element data form. More...
 
virtual void Rotate (bool clockwise=true)
 Rotate the element. More...
 
virtual std::vector< Signal > GetSignalList () const
 
virtual void SetSignalList (std::vector< Signal > signalList)
 
virtual bool Solve (double *input, double timeStep)
 
virtual void UpdatePoints ()
 
void AddInNode ()
 
void RemoveInNode ()
 
virtual rapidxml::xml_node * SaveElement (rapidxml::xml_document<> &doc, rapidxml::xml_node<> *elementListNode)
 
virtual bool OpenElement (rapidxml::xml_node<> *elementNode)
 
virtual ElementGetCopy ()
 Get a the element copy. More...
 
- Public Member Functions inherited from ControlElement
 ControlElement (int id)
 
virtual void StartMove (wxPoint2DDouble position)
 Update the element attributes related to the movement. More...
 
virtual void Move (wxPoint2DDouble position)
 Move the element other position. More...
 
void SetNodeList (std::vector< Node *> nodeList)
 
std::vector< Node * > GetNodeList () const
 
virtual void DrawNodes () const
 
virtual void ReplaceNode (Node *oldNode, Node *newNode)
 
virtual bool UpdateText ()
 Update the OpenGL text in the element (if present). More...
 
virtual bool IsSolved () const
 
virtual void SetSolved (bool solved=true)
 
virtual bool Initialize ()
 
virtual double GetOutput () const
 
virtual void SetOutput (double output)
 
- Public Member Functions inherited from Element
 Element ()
 Constructor.
 
virtual ~Element ()
 Destructor.
 
void SetDragging (bool dragging=true)
 Set if the element are being dragged. More...
 
void SetHeight (double height)
 Set element height. More...
 
void SetPosition (const wxPoint2DDouble position)
 Set the element position and update the rectangle. More...
 
void SetSelected (bool selected=true)
 Set element selection. More...
 
void SetWidth (double width)
 Set element width. More...
 
void SetAngle (double angle)
 Set element angle. More...
 
void ShowPickbox (bool showPickbox=true)
 Set if the pickbox is shown. More...
 
void SetBorderSize (double borderSize)
 Set the size of the border (shown in selected elements). More...
 
bool SetOnline (bool online=true)
 Set if the element is online or offline. More...
 
virtual void SetPointList (std::vector< wxPoint2DDouble > pointList)
 Set the list of points that connect the element to the bus. More...
 
wxRect2DDouble GetRect () const
 Get the element rectangle. More...
 
wxPoint2DDouble GetPosition () const
 Get the element position. More...
 
bool IsDragging () const
 Checks if the element is being dragged. More...
 
double GetHeight () const
 Get the element height. More...
 
bool IsSelected () const
 Checks if the element is selected. More...
 
double GetWidth () const
 Get the element width. More...
 
double GetAngle () const
 Get the element angle. More...
 
double GetRotationAngle () const
 Get the angle of rotation. More...
 
bool IsPickboxShown () const
 Checks if the pickbox is shown. More...
 
bool IsOnline () const
 Checks if the element is online or offline. More...
 
virtual std::vector< wxPoint2DDouble > GetPointList () const
 Get the list of points that connect the element to bus. More...
 
virtual bool AddParent (Element *parent, wxPoint2DDouble position)
 Add a parent to the element. This method must be used on power elements that connect to a bus, so the parent must be a bus. The element basic points are calculated in this method, so apply this when the element is being inserted. More...
 
virtual void AddParent (Element *parent)
 Add a parent to the element. More...
 
virtual void SetID (int id)
 Set the element ID. More...
 
virtual int GetID () const
 Get the element ID. More...
 
virtual void AddChild (Element *child)
 Add a child to the child list. More...
 
virtual void RemoveChild (Element *child)
 Remove a child from the list. More...
 
virtual void ReplaceChild (Element *oldChild, Element *newChild)
 Replace a child from the list. More...
 
virtual wxString GetTipText () const
 Get the tip text. More...
 
virtual bool GetContextMenu (wxMenu &menu)
 Get the element contex menu. More...
 
virtual void AddPoint (wxPoint2DDouble point)
 Add point to the list of points that connect the element to the bus. More...
 
virtual void MoveNode (Element *parent, wxPoint2DDouble position)
 Move a node. StartMove(wxPoint2DDouble position) before start moving. More...
 
virtual bool NodeContains (wxPoint2DDouble position)
 Check if a node contains a point. If contains, set the attributes related to node movement. More...
 
virtual void UpdateNodes ()
 Update the nodes according to the parents. If a parent is removed, use this method.
 
virtual bool SetNodeParent (Element *parent)
 Set a perent to the node. If all conditions are met, a new parent are added to the element and the points related to the nodes will be calculated. More...
 
virtual void RemoveParent (Element *parent)
 Remove a parent. More...
 
virtual void ReplaceParent (Element *oldParent, Element *newParent)
 Replace a parent. More...
 
virtual void RotateNode (Element *parent, bool clockwise=true)
 Rotate a node. More...
 
virtual bool PickboxContains (wxPoint2DDouble position)
 Check if a pickbox contains a point. If contains the attributes related to pickbox movement will be calculated. More...
 
virtual void MovePickbox (wxPoint2DDouble position)
 Move the pickbox. More...
 
virtual wxCursor GetBestPickboxCursor () const
 Get the best cursor to shown to the user when the mouse is above a pickbox. More...
 
virtual void ResetPickboxes ()
 Remove the pickboxes.
 
virtual void ResetNodes ()
 Remove the active nodes.
 
virtual wxPoint2DDouble WorldToScreen (wxPoint2DDouble translation, double scale, double offsetX=0.0, double offsetY=0.0) const
 Convert the element position to screen position. More...
 
virtual wxPoint2DDouble WorldToScreen (wxPoint2DDouble position, wxPoint2DDouble translation, double scale, double offsetX=0.0, double offsetY=0.0) const
 Convert a generic position to screen position. More...
 
virtual bool RotatedRectanglesIntersects (wxRect2DDouble rect1, wxRect2DDouble rect2, double angle1, double angle2) const
 Check if two roteted rectangles intersect. More...
 
virtual void DrawCircle (wxPoint2DDouble position, double radius, int numSegments, GLenum mode=GL_LINE_LOOP) const
 Draw a circle. More...
 
virtual void DrawArc (wxPoint2DDouble position, double radius, double initAngle, double finalAngle, int numSegments, GLenum mode=GL_LINE_LOOP) const
 
virtual void DrawRectangle (wxPoint2DDouble position, double width, double height, GLenum mode=GL_QUADS) const
 Draw rectangle. More...
 
virtual void DrawRectangle (wxPoint2DDouble *points, GLenum mode=GL_QUADS) const
 Draw rectangle. More...
 
virtual void DrawTriangle (std::vector< wxPoint2DDouble > points, GLenum mode=GL_TRIANGLES) const
 Draw a triangle. More...
 
virtual void DrawPoint (wxPoint2DDouble position, double size) const
 Draw a point. More...
 
virtual void DrawLine (std::vector< wxPoint2DDouble > points, GLenum mode=GL_LINE_STRIP) const
 Draw line. More...
 
virtual void DrawPickbox (wxPoint2DDouble position) const
 Draw pickbox. More...
 
virtual wxPoint2DDouble RotateAtPosition (wxPoint2DDouble pointToRotate, double angle, bool degrees=true) const
 Rotate a point as element position being the origin. More...
 
virtual std::vector< Element * > GetParentList () const
 Get the parent list. More...
 
virtual std::vector< Element * > GetChildList () const
 Get the Child list. More...
 
virtual void CalculateBoundaries (wxPoint2DDouble &leftUp, wxPoint2DDouble &rightBottom) const
 Calculate the element boundaries. More...
 
virtual void GeneralMenuItens (wxMenu &menu)
 Insert general itens to context menu. More...
 
virtual double PointToLineDistance (wxPoint2DDouble point, int *segmentNumber=NULL) const
 Calculate the distance between a line (formed by point list) and a point. More...
 
void SaveCADProperties (rapidxml::xml_document<> &doc, rapidxml::xml_node<> *elementNode)
 
bool OpenCADProperties (rapidxml::xml_node<> *elementNode)
 

Protected Attributes

std::vector< Signal > m_signalList
 
- Protected Attributes inherited from ControlElement
std::vector< Node * > m_nodeList
 
bool m_solved = false
 
double m_output = 0.0
 
- Protected Attributes inherited from Element
int m_elementID = 0
 
std::vector< Element * > m_parentList
 
std::vector< Element * > m_childList
 
wxRect2DDouble m_rect
 
wxPoint2DDouble m_position
 
double m_width = 0.0
 
double m_height = 0.0
 
double m_angle = 0.0
 
double m_borderSize = 2.0
 
double m_rotationAngle = 45.0
 
double m_switchSize = 10.0
 
std::vector< wxRect2DDouble > m_switchRect
 
bool m_selected = false
 
bool m_dragging = false
 
bool m_showPickbox = false
 
int m_activePickboxID = ID_PB_NONE
 
int m_activeNodeID = 0
 
std::vector< wxPoint2DDouble > m_pointList
 
std::vector< wxPoint2DDouble > m_movePts
 
wxPoint2DDouble m_moveStartPt
 
wxPoint2DDouble m_movePos
 
bool m_online = true
 
OpenGLColour m_selectionColour
 

Additional Inherited Members

- Static Public Member Functions inherited from ControlElement
static ControlElementGetControlElementFromID (std::vector< ControlElement *> elementList, int id)
 
- Static Public Member Functions inherited from Element
static bool DoubleFromString (wxWindow *parent, wxString strValue, double &value, wxString errorMsg)
 Get a double value from a string. Show a error message if the conversion fail. More...
 
static bool IntFromString (wxWindow *parent, wxString strValue, int &value, wxString errorMsg)
 Convert a string to int. Show a error message if the conversion fail. More...
 
static wxString StringFromDouble (double value, int minDecimal=1)
 Convert a double value to string. More...
 
- Protected Member Functions inherited from ControlElement
void SaveControlNodes (rapidxml::xml_document<> &doc, rapidxml::xml_node<> *elementNode)
 
bool OpenControlNodes (rapidxml::xml_node<> *elementNode)
 

Detailed Description

Sum the all inputs (can choose the input signal).

Author
Thales Lima Oliveira thale.nosp@m.s@uf.nosp@m.u.br
Date
06/10/2017

Member Function Documentation

◆ Contains()

virtual bool Sum::Contains ( wxPoint2DDouble  position) const
inlinevirtual

Checks if the element contains a position.

Parameters
positionPosition to be checked.

Implements Element.

◆ Draw()

void Sum::Draw ( wxPoint2DDouble  translation,
double  scale 
) const
virtual

Draw the element.

Parameters
translationTranslation of the system.
scaleScale of the system.

Reimplemented from Element.

◆ GetCopy()

Element * Sum::GetCopy ( )
virtual

Get a the element copy.

Returns
Copy of the element.

Reimplemented from Element.

◆ Intersects()

virtual bool Sum::Intersects ( wxRect2DDouble  rect) const
inlinevirtual

Check if the element's rect intersects other rect.

Parameters
rectRect to check intersection.

Implements Element.

◆ Rotate()

void Sum::Rotate ( bool  clockwise = true)
virtual

Rotate the element.

Parameters
clockwiseTrue to rotate clockwise, false to rotate counter-clockwise.

Reimplemented from Element.

◆ ShowForm()

bool Sum::ShowForm ( wxWindow *  parent,
Element element 
)
virtual

Show element data form.

Parameters
parentForm parent
elementElement that will be edited.
Returns
True if the form is shown, false otherwise.

Reimplemented from Element.


The documentation for this class was generated from the following files:
id='n2367' href='#n2367'>2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248
// --- BEGIN COPYRIGHT BLOCK ---
// This library 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;
// version 2.1 of the License.
// 
// This library 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 this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA 
// 
// Copyright (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

/**
 *  RA_Enroll_Processor handles initialization and enrollment of the token
 */


/* variable naming convention:
 * a_ passed as an 'in' argument to a method
 * o_ passed as an 'out' argument to a method
 * m_ member variable
 */


#include <string.h>
#include <time.h>
#include "pkcs11.h"

// for public key processing
#include "secder.h"
#include "pk11func.h"
#include "cryptohi.h"
#include "keyhi.h"
#include "base64.h"
#include "nssb64.h"
#include "prlock.h"

#include "cert.h"
#include "main/RA_Session.h"
#include "main/RA_Msg.h"
#include "main/Buffer.h"
#include "main/Util.h"
#include "main/PKCS11Obj.h"
#include "engine/RA.h"
#include "channel/Secure_Channel.h"
#include "msg/RA_SecureId_Request_Msg.h"
#include "msg/RA_SecureId_Response_Msg.h"
#include "msg/RA_New_Pin_Request_Msg.h"
#include "msg/RA_New_Pin_Response_Msg.h"
#include "processor/RA_Processor.h"
#include "processor/RA_Enroll_Processor.h"
#include "tus/tus_db.h"

#include "cms/CertEnroll.h"
#include "httpClient/httpc/response.h"
#include "main/Memory.h"

#define OP_PREFIX "op.enroll"

#ifdef XP_WIN32
#define TPS_PUBLIC __declspec(dllexport)
#else /* !XP_WIN32 */
#define TPS_PUBLIC
#endif /* !XP_WIN32 */

SECStatus PK11_GenerateRandom(unsigned char *,int);
void PrintPRTime(PRTime, const char *);


// This parameter is read from the config file. It is the
// applet build ID which the administrator wants to set as
// the 'latest applet' to upgrade to.
static const char *g_applet_target_version = NULL;


/**
 * this function returns a new allocated string
 * @param cuid a 20 character string. Usually this is 20 hex
 *  digits representing a token CUID.
 * @returns a new string which is basically a copy of the input, but 
 *   with extra colons. The caller is responsible for freeing the 
 *   returned string with PR_Free().
 */

static char *GetPrettyPrintCUID(const char *cuid)
{
	int i,j;
	char *ret = NULL;

	if (cuid == NULL)
		return NULL;
	if (strlen(cuid) != 20) 
		return NULL;
	ret = (char *)PR_Malloc(20+4+1);
	j = 0;
	for (i = 0; i < 24; i++) {
		if (i == 4 || i == 9 || i == 14 || i == 19) {
		    ret[i] = '-';
		} else {
		    ret[i] = cuid[j];
		    j++;
		}
	}
	ret[24] = '\0';
	return ret;
}

static SECItem *
PK11_GetPubIndexKeyID(CERTCertificate *cert) {
    SECKEYPublicKey *pubk;
    SECItem *newItem = NULL;
                                                                                
    pubk = CERT_ExtractPublicKey(cert);
    if (pubk == NULL) return NULL;
                                                                                
    switch (pubk->keyType) {
    case rsaKey:
    newItem = SECITEM_DupItem(&pubk->u.rsa.modulus);
    break;
    case dsaKey:
        newItem = SECITEM_DupItem(&pubk->u.dsa.publicValue);
    break;
    case dhKey:
        newItem = SECITEM_DupItem(&pubk->u.dh.publicValue);
    break;
    case ecKey:
        newItem = SECITEM_DupItem(&pubk->u.ec.publicValue);
    break;
    case fortezzaKey:
    default:
    newItem = NULL; /* Fortezza Fix later... */
    }
    SECKEY_DestroyPublicKey(pubk);
    /* make hash of it */
    return newItem;
}


/**
 * Constructs a processor for handling enrollment operation.
 */
TPS_PUBLIC RA_Enroll_Processor::RA_Enroll_Processor ()
{
}

/**
 * Destructs enrollment processor.
 */
TPS_PUBLIC RA_Enroll_Processor::~RA_Enroll_Processor ()
{
}

RA_Status RA_Enroll_Processor::DoEnrollment(AuthParams *login, RA_Session *session, 
                CERTCertificate **certificates,
                char **origins,
                char **ktypes,
		    int pkcs11obj_enable,
		PKCS11Obj *pkcs_objx,
		NameValueSet *extensions,
		int index, int keyTypeNum,
		int start_progress,
		int end_progress,
		Secure_Channel *channel, Buffer *wrapped_challenge,
		const char *tokenType,
		const char *keyType,
		Buffer *key_check, 
		Buffer *plaintext_challenge,
		const char *cuid,
		const char *msn,
		const char *khex, 
		TokenKeyType key_type,
		const char *profileId,
		const char *userid, 
		const char *cert_id, 
                const char *publisher_id,
		const char *cert_attr_id, 
		const char *pri_attr_id,
		const char *pub_attr_id, 
		BYTE se_p1, BYTE se_p2, BYTE algorithm,  int keysize, const char *connid, const char *keyTypePrefix,char * applet_version)
{
    RA_Status status = STATUS_NO_ERROR;
    int rc = -1;
    int len = 0;
    int publish_result = -1;
    Buffer *public_key = NULL;
    SECItem si_mod;
    Buffer *modulus=NULL;
    SECItem *si_kid = NULL;
    Buffer *keyid=NULL;
    SECItem si_exp;
    Buffer *exponent=NULL;
    CertEnroll *certEnroll = NULL;
    Buffer *cert = NULL;
    Buffer CUID = channel->GetKeyDiversificationData();
    const char *label = NULL;
    const char *cuid_label = NULL;
    const char *pattern;
    char configname[256];
    NameValueSet nv;
    const char *pretty_cuid = NULL;

    const char *FN="RA_Enroll_Processor::DoEnrollment";

    char *cert_string = NULL;
    SECItem* encodedPublicKeyInfo = NULL;
    SECItem **ppEncodedPublicKeyInfo = NULL;
	CERTSubjectPublicKeyInfo*  spkix = NULL;

    char *pKey = NULL;
    char *ivParam = NULL;
    char *wrappedPrivKey = NULL;

    const char *drmconnid = NULL;
    bool serverKeygen = false;
    SECKEYPublicKey *pk_p = NULL;

    char audit_msg[512] = "";
    char *keyVersion = NULL;
    char cert_serial[2048] = "";
    char activity_msg[4096] = "";

    float progress_block_size = (float) (end_progress - start_progress) / keyTypeNum;
    RA::Debug(LL_PER_CONNECTION,FN,
	            "Start of keygen/certificate enrollment");

    bool isECC = RA::isAlgorithmECC(algorithm);
    SECKEYECParams  *eccParams = NULL;

    // get key version for audit logs
    if (channel != NULL) {
       if( keyVersion != NULL ) {
           PR_Free( (char *) keyVersion );
           keyVersion = NULL;
       }
       keyVersion = Util::Buffer2String(channel->GetKeyInfoData());
    }

    // check if we need to do key generation (by default, overwrite everything)
    PR_snprintf((char *)configname, 256, "%s.%s.keyGen.%s.overwrite", 
		    OP_PREFIX, tokenType, keyType);
      RA::Debug(LL_PER_CONNECTION,FN,
	            "looking for config %s", configname);
    if (RA::GetConfigStore()->GetConfigAsBool(configname, 1)) {
	    // do nothing
      RA::Debug(LL_PER_CONNECTION,FN,
	            "do overwrite");
    } else {
      RA::Debug(LL_PER_CONNECTION,FN,
	            "do not overwrite, if %s exists", cert_id);
      int num_objs = pkcs_objx->PKCS11Obj::GetObjectSpecCount();
      char b[3];
      bool foundObj = false;
      for (int i = 0; i< num_objs; i++) {
	ObjectSpec* os = pkcs_objx->GetObjectSpec(i);
	unsigned long oid = os->GetObjectID();
	b[0] = (char)((oid >> 24) & 0xff);
	b[1] = (char)((oid >> 16) & 0xff);
	b[2] = '\0';
	/*
	RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
		   "object id =%c:%c  b=%s",b[0], b[1], b);
	*/
	if (PL_strcasecmp(cert_id, b) == 0) {
	  foundObj = true;
	  break;
	}
      }


      if (foundObj) {
		// we already have a certificate there, skip enrollment
                RA::Debug(LL_PER_CONNECTION,FN,
	            "Found certficate. Will not overwrite. Skipped enrollment");
		return status;
	} else {
                RA::Debug(LL_PER_CONNECTION,FN,
	            "Certficate not found. Continuing with enrollment");
	}
    }
    
    StatusUpdate(session, extensions, 
		 start_progress + (index * progress_block_size) + 
		 (progress_block_size * 15/100) /* progress */, 
		 "PROGRESS_KEY_GENERATION");

    if (key_type == KEY_TYPE_ENCRYPTION) {
      // do serverSide keygen?
      PR_snprintf((char *)configname, 256, "%s.serverKeygen.enable", keyTypePrefix);
      RA::Debug(LL_PER_CONNECTION,FN,
		"looking for config %s", configname);
      serverKeygen = RA::GetConfigStore()->GetConfigAsBool(configname, false);
    }

    certEnroll = new CertEnroll();

    if (serverKeygen) {
      RA::Debug(LL_PER_CONNECTION,FN,
        "Private key is to be generated on server");

      PR_snprintf((char *)configname, 256, "%s.serverKeygen.drm.conn", keyTypePrefix);
      RA::Debug(LL_PER_CONNECTION,FN,
        "looking for config %s", configname);
      drmconnid = RA::GetConfigStore()->GetConfigAsString(configname);

      PR_snprintf((char *)configname, 256, "%s.serverKeygen.archive", keyTypePrefix);
      bool archive = RA::GetConfigStore()->GetConfigAsBool(configname, true);

      RA::Debug(LL_PER_CONNECTION,FN,
        "calling ServerSideKeyGen with userid =%s, archive=%s", userid, archive? "true":"false");

      RA::ServerSideKeyGen(session, cuid, userid,
                           channel->getDrmWrappedDESKey(), &pKey,
                           &wrappedPrivKey, &ivParam, drmconnid,
                           archive, keysize, isECC);

      if (pKey == NULL) {
        RA::Error(LL_PER_CONNECTION,FN,
          "Failed to generate key on server. Please check DRM.");
        RA::Debug(LL_PER_CONNECTION,FN,
          "ServerSideKeyGen called, pKey is NULL");
        status = STATUS_ERROR_MAC_ENROLL_PDU;

        PR_snprintf(audit_msg, 512, "ServerSideKeyGen called, failed to generate key on server");
        goto loser;
      } else {
        RA::Debug(LL_PER_CONNECTION,FN,
          "key value = %s", pKey);
      }


      if (wrappedPrivKey == NULL) {
        RA::Debug(LL_PER_CONNECTION,FN,
          "ServerSideKeyGen called, wrappedPrivKey is NULL");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "ServerSideKeyGen called, wrappedPrivKey is NULL");
        goto loser;
      } else {
        RA::Debug(LL_PER_CONNECTION,FN,
          "wrappedPrivKey = %s", wrappedPrivKey);
      }

      if (ivParam == NULL) {
        RA::Debug(LL_PER_CONNECTION,FN,
          "ServerSideKeyGen called, ivParam is NULL");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "ServerSideKeyGen called, ivParam is NULL");
        goto loser;
      } else
        RA::Debug(LL_PER_CONNECTION,FN, "ivParam = %s", ivParam);

      /*
       * the following code converts b64-encoded public key info into SECKEYPublicKey
       */
      SECStatus rv;
      SECItem der;
      CERTSubjectPublicKeyInfo* spki = NULL;
               
      Buffer *decodePubKey = Util::URLDecode(pKey);
      char *pKey_ascii = NULL;
      if (decodePubKey != NULL) {
          pKey_ascii = 
              BTOA_DataToAscii(decodePubKey->getBuf(), decodePubKey->size());
            
      } else {
          PR_snprintf(audit_msg, 512, "ServerSideKeyGen: failed to URL decode public key");
        goto loser;
      }

      der.type = (SECItemType) 0; /* initialize it, since convertAsciiToItem does not set it */
      rv = ATOB_ConvertAsciiToItem (&der, pKey_ascii);
      if (rv != SECSuccess){
        RA::Debug(LL_PER_CONNECTION,FN,
          "failed to convert b64 public key to binary");
        SECITEM_FreeItem(&der, PR_FALSE);
        status = STATUS_ERROR_MAC_ENROLL_PDU;
          PR_snprintf(audit_msg, 512, "ServerSideKeyGen: failed to convert b64 public key to binary");
        goto loser;
      } else {
        RA::Debug(LL_PER_CONNECTION,FN,
          "decoded public key as: secitem (len=%d)",der.len);

        spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&der);

        if (spki != NULL) {
          RA::Debug(LL_PER_CONNECTION,FN,
            "Successfully decoded DER SubjectPublicKeyInfo structure");
          pk_p = SECKEY_ExtractPublicKey(spki);
          if (pk_p != NULL)
            RA::Debug(LL_PER_CONNECTION,FN, "Successfully extracted public key from SPKI structure");
          else
            RA::Debug(LL_PER_CONNECTION,FN, "Failed to extract public key from SPKI");
        } else {
          RA::Debug(LL_PER_CONNECTION,FN,
            "Failed to decode SPKI structure");
        }

        SECITEM_FreeItem(&der, PR_FALSE);
            SECKEY_DestroySubjectPublicKeyInfo(spki);
      }

    } else { //generate keys on token

      RA::Debug(LL_PER_CONNECTION,FN,
                "Private key is to be generated on token");

      BYTE alg = 0x80;

      if(key_check && key_check->size())
         alg = 0x81;


      if (isECC) {
         alg = algorithm;
      }

      len = channel->StartEnrollment(
        se_p1, se_p2,
        wrapped_challenge,
        key_check,
        alg /* alg */, keysize,
        0x00 /* option */);

      RA::Debug(LL_PER_CONNECTION,FN,
          "channel->StartEnrollment returned length of public key blob: len=%d", len);

	StatusUpdate(session, extensions,
			start_progress + (index * progress_block_size) + 
			(progress_block_size * 45/100) /* progress */, 
			"PROGRESS_READ_PUBLIC_KEY");

      /* read the public key from buffer */
      if (len <= 0) {
	RA::Error(LL_PER_CONNECTION,FN,
		  "Error generating key on token.");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "Error generating key on token");
        goto loser;
      }

      RA::Debug(LL_PER_CONNECTION,FN,
		"Reading public key buffer from token");

      BYTE iobuf[4];
      iobuf[0] = 0xff;
      iobuf[1] = 0xff;
      iobuf[2] = 0xff;
      iobuf[3] = 0xff;
      /* use ReadObject to read IO buffer */
      public_key = channel->ReadObject(iobuf, 0, len);
      if (public_key == NULL) {
	RA::Error(LL_PER_CONNECTION,FN,
		  "Unable to read public key buffer from token");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "Unable to read public key buffer from token");
        goto loser;
      }
      RA::Debug(LL_PER_CONNECTION,FN,
	      "Successfully read public key buffer");
      
      RA::DebugBuffer(LL_PER_CONNECTION,FN,
		"public_key = ", public_key);

      //got public key blob
      // parse public key blob and check POP

      RA::Debug(LL_PER_CONNECTION,FN,
	      "challenge size=%d",plaintext_challenge->size());
      RA::DebugBuffer("RA_Enroll_Processor::process", "challenge = ", 
          plaintext_challenge);


      // We have received the public key blob for ECC

      // send status update to the client
	StatusUpdate(session, extensions,
			start_progress + (index * progress_block_size) + 
			(progress_block_size * 55/100) /* progress */, 
			"PROGRESS_PARSE_PUBLIC_KEY");

      RA::Debug(LL_PER_CONNECTION,FN,
		"About to Parse Public Key");

      pk_p = certEnroll->ParsePublicKeyBlob(
                (unsigned char *)(BYTE *)*public_key /*blob*/, 
                plaintext_challenge, isECC);

      if (pk_p == NULL) {
	    RA::Error(LL_PER_CONNECTION,FN,
		  "Failed to parse public key");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "Failed to parse public key");
        goto loser;
      }

    } //serverKeygen or not

    RA::Debug(LL_PER_CONNECTION,FN,
		"Keys generated. Proceeding with certificate enrollment");

    RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
          userid != NULL ? userid : "",
          cuid != NULL ? cuid : "",
          msn != NULL ? msn : "",
          "success",
          "enrollment",
          applet_version != NULL ? applet_version : "",
          keyVersion != NULL? keyVersion : "",
          "keys generated");

    if(publisher_id != NULL)
    {
        ppEncodedPublicKeyInfo = &encodedPublicKeyInfo;

    }

    pretty_cuid = GetPrettyPrintCUID(cuid);

    nv.Add("pretty_cuid", pretty_cuid);
    nv.Add("cuid", cuid);
    nv.Add("msn", msn);
    nv.Add("userid", userid);
    nv.Add("profileId", profileId);

    /* populate auth parameters output to nv also */
    /* so we can reference to the auth parameter by */
    /* using $auth.cn$, or $auth.mail$ */
    if (login != NULL) {
      int s = login->Size();
      for (int x = 0; x < s; x++) {
         char namebuf[2048];
         char *name = login->GetNameAt(x);
         sprintf(namebuf, "auth.%s", name);
         nv.Add(namebuf, login->GetValue(name));
      }
    }

    PR_snprintf((char *)configname, 256, "%s.%s.keyGen.%s.cuid_label", 
		    OP_PREFIX, tokenType, keyType);

    RA::Debug(LL_PER_CONNECTION,FN,
		"Certificate label '%s'", configname);

    pattern = RA::GetConfigStore()->GetConfigAsString(configname, "$cuid$");
    cuid_label = MapPattern(&nv, (char *) pattern);

	StatusUpdate(session, extensions,
			start_progress + (index * progress_block_size) + 
			(progress_block_size * 60/100) /* progress */, 
			"PROGRESS_ENROLL_CERT");

    cert = certEnroll->EnrollCertificate(
                    pk_p, profileId, userid, cuid_label, 
		    connid, audit_msg, ppEncodedPublicKeyInfo);

    if (cert == NULL) {
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC_CERT_REQ, 
          userid, cuid, msn, "failure", "enrollment", applet_version, 
          keyVersion != NULL ? keyVersion : "", 
          "", connid,  audit_msg);
        goto loser;
    }

    if (!isECC) {
        si_mod = pk_p->u.rsa.modulus;
        modulus = new Buffer((BYTE*) si_mod.data, si_mod.len);
    }

    /* 
     * RFC 3279
     * The keyIdentifier is composed of the 160-bit SHA-1 hash of the
     * value of the BIT STRING subjectPublicKey (excluding the tag,
     * length, and number of unused bits).
     */
	spkix = SECKEY_CreateSubjectPublicKeyInfo(pk_p);

    /* 
     * NSS magically multiply the length with 2^3 in cryptohi/seckey.c 
     * Hack: 
     */
    spkix->subjectPublicKey.len >>= 3;
    si_kid = PK11_MakeIDFromPubKey(&spkix->subjectPublicKey);
    spkix->subjectPublicKey.len <<= 3;

    keyid = new Buffer((BYTE*) si_kid->data, si_kid->len);

    if (!isECC) {
        si_exp = pk_p->u.rsa.publicExponent;
        exponent =  new Buffer((BYTE*) si_exp.data, si_exp.len);
        RA::Debug(LL_PER_CONNECTION,FN,
            "Keyid, modulus and exponent have been extracted from public key");
    }

    SECKEY_DestroySubjectPublicKeyInfo(spkix);

    cert_string = (char *) cert->string();
    certificates[index] = CERT_DecodeCertFromPackage((char *) cert_string, 
      (int) cert->size());
    if (certificates[index] != NULL) {
        RA::ra_tus_print_integer(cert_serial, &certificates[index]->serialNumber);
        RA::Debug("DoEnrollment", "Received Certificate");
        RA::Debug("DoEnrollment", cert_serial);

        RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC_CERT_REQ, 
          userid, cuid, msn, "success", "enrollment", applet_version, 
          (keyVersion != NULL) ? keyVersion : "", cert_serial, connid,  "certificate received");
    }
    free(cert_string);
    ktypes[index] = PL_strdup(keyType);
    origins[index] = PL_strdup(cuid);

    if (serverKeygen) {
      //do PKCS#8

      BYTE objid[4];

      objid[0] = 0xFF;
      objid[1] = 0x00;
      objid[2] = 0xFF;
      objid[3] = 0xF3;
      Buffer priv_keyblob;
      /* url decode wrappedPrivKey */
      {
	Buffer *decodeKey = Util::URLDecode(wrappedPrivKey);
	// RA::DebugBuffer("cfu debug"," private key =",decodeKey);
	priv_keyblob =
	  Buffer(1, 0x01) + // encryption
	  Buffer(1, 0x09)+ // keytype is RSAPKCS8Pair
	  Buffer(1,(BYTE)(keysize/256)) + // keysize is two bytes
	  Buffer(1,(BYTE)(keysize%256)) +
	  Buffer((BYTE*) *decodeKey, decodeKey->size());
	delete decodeKey;
      }

      //inject PKCS#8 private key
      BYTE perms[6];

      perms[0] = 0x40;
      perms[1] = 0x00;
      perms[2] = 0x40;
      perms[3] = 0x00;
      perms[4] = 0x40;
      perms[5] = 0x00;

      if (channel->CreateObject(objid, perms, priv_keyblob.size()) != 1) {
	status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "ServerSideKeyGen: store keys in token failed, channel create object error");
	goto loser;
      }


      if (channel->WriteObject(objid, (BYTE*)priv_keyblob, priv_keyblob.size()) != 1) {
	status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "ServerSideKeyGen: store keys in token failed, channel write object error");
	goto loser;
      }


      /* url decode the wrapped kek session key and keycheck*/
      Buffer data;
      {

	/*
	  RA::Debug(LL_PER_PDU, "", "getKekWrappedDESKey() returns =%s", channel->getKekWrappedDESKey());
	  RA::Debug(LL_PER_PDU, "", "getKeycheck() returns =%s", channel->getKeycheck());
	*/
	Buffer *decodeKey = Util::URLDecode(channel->getKekWrappedDESKey());

	/*
	  RA::Debug(LL_PER_PDU, "", "des key item len=%d",
	  decodeKey->size());
	  RA::DebugBuffer("cfu debug", "DES key =", decodeKey);
	*/
	char *keycheck = channel->getKeycheck();
	Buffer *decodeKeyCheck = Util::URLDecode(keycheck);
	if (keycheck)
	  PL_strfree(keycheck);

	/*
	  RA::Debug(LL_PER_PDU, "", "keycheck item len=%d",
	  decodeKeyCheck->size());
	  RA::DebugBuffer("cfu debug", "key check=", decodeKeyCheck);
	*/

	//XXX need randomize this later

	//	  BYTE iv[] = {0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01};
	// get ivParam
	Buffer *iv_decoded = Util::URLDecode(ivParam);
	if (ivParam) {
	  PL_strfree(ivParam);
	}

        if(iv_decoded == NULL) {
           status = STATUS_ERROR_MAC_ENROLL_PDU;
           PR_snprintf(audit_msg, 512, "ServerSideKeyGen: store keys in token failed, iv data not found");
           delete decodeKey;
           delete decodeKeyCheck;
           goto loser; 
        }

        BYTE alg = 0x80;
        if(decodeKey && decodeKey->size()) {
            alg = 0x81;
        }

	data =
	  Buffer((BYTE*)objid, 4)+ // object id
	  Buffer(1,alg) +
	  Buffer(1, (BYTE) decodeKey->size()) + // 1 byte length
	  Buffer((BYTE *) *decodeKey, decodeKey->size())+ // key -encrypted to 3des block
	  // check size
	  // key check
	  Buffer(1, (BYTE) decodeKeyCheck->size()) + //keycheck size
	  Buffer((BYTE *) *decodeKeyCheck , decodeKeyCheck->size())+ // keycheck
	  Buffer(1, iv_decoded->size())+ // IV_Length
	  Buffer((BYTE*)*iv_decoded, iv_decoded->size());

	delete iv_decoded;
	//      RA::DebugBuffer("cfu debug", "ImportKeyEnc data buffer =", &data);

	delete decodeKey;
	delete decodeKeyCheck;
      }

      if (channel->ImportKeyEnc(se_p1, se_p2, &data) != 1) {
	status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "ServerSideKeyGen: store keys in token failed, channel import key error");
	goto loser;
      }

      RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
          userid != NULL ? userid : "",
          cuid != NULL ? cuid : "",
          msn != NULL ? msn : "",
          "success",
          "enrollment",
          applet_version != NULL ? applet_version : "",
          keyVersion != NULL? keyVersion : "",
          "server generated keys stored in token");


      /*
       * After keys are injected successfully, then write certificate object apdu
       * to token
       */

    } // serverKeygen


    StatusUpdate(session, extensions,
		 start_progress + (index * progress_block_size) + 
		 (progress_block_size * 70/100) /* progress */, 
		 "PROGRESS_PUBLISH_CERT");

    //Attempt publish if relevant
    if(ppEncodedPublicKeyInfo)
      { 

        publish_result = DoPublish(cuid,encodedPublicKeyInfo,cert,publisher_id,applet_version); 

      }

    if(ppEncodedPublicKeyInfo)
      {
	RA::Debug(LL_PER_CONNECTION,FN,
			"Deleting PublicKeyInfo object.");

	SECITEM_FreeItem(*ppEncodedPublicKeyInfo, PR_TRUE);
      }

    if(publish_result == 0)
      {
        status = STATUS_ERROR_PUBLISH;

        RA::Error(LL_PER_CONNECTION,FN,
		 "Enroll Certificate Publish Failure %d", status);

        RA::Debug(LL_PER_CONNECTION,FN,
		"Enroll Certificate Publish Failure %d",status);
        PR_snprintf(audit_msg, 512, "publish certificate error");
        goto loser;
      }

    if (cert != NULL) {
      RA::Debug(LL_PER_CONNECTION,FN,
		"Enroll Certificate Finished");
    } else {
      RA::Error(LL_PER_CONNECTION,FN,
	"Enroll Certificate Failure");

        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "cert is null");
        goto loser;
    }

	StatusUpdate(session, extensions,
			start_progress + (index * progress_block_size) + 
			(progress_block_size * 80/100) /* progress */, 
			"PROGRESS_IMPORT_CERT");

    /* write certificate from CA to netkey */
    if (pkcs11obj_enable) {
        ObjectSpec *objSpec = 
          ObjectSpec::ParseFromTokenData(
           (cert_id[0] << 24) +
           (cert_id[1] << 16),
           cert);
       pkcs_objx->AddObjectSpec(objSpec);
    } else {
        RA::Debug(LL_PER_CONNECTION,FN,
          "About to create certificate object on token");
        rc = channel->CreateCertificate(cert_id, cert);
        if (rc == -1) {
          RA::Error(LL_PER_CONNECTION,FN,
            "Failed to create certificate object on token");
          status = STATUS_ERROR_MAC_ENROLL_PDU;
            PR_snprintf(audit_msg, 512, "Failed to create certificate object on token");
          goto loser;
        }
    }

    // build label
    PR_snprintf((char *)configname, 256, "%s.%s.keyGen.%s.label", 
      OP_PREFIX, tokenType, keyType);
    RA::Debug(LL_PER_CONNECTION,FN,
      "label '%s'", configname);
    pattern = RA::GetConfigStore()->GetConfigAsString(configname);
    label = MapPattern(&nv, (char *) pattern);

    if (pkcs11obj_enable) {
        Buffer b = channel->CreatePKCS11CertAttrsBuffer(
                        key_type, cert_attr_id, label, keyid);
        ObjectSpec *objSpec = 
                ObjectSpec::ParseFromTokenData(
                                (cert_attr_id[0] << 24) +
                                (cert_attr_id[1] << 16),
                                &b);
        pkcs_objx->AddObjectSpec(objSpec);
    } else {
        RA::Debug(LL_PER_CONNECTION,FN,
            "About to create PKCS#11 certificate Attributes");
        rc = channel->CreatePKCS11CertAttrs(key_type, cert_attr_id, label, keyid);
        if (rc == -1) {
            RA::Error(LL_PER_CONNECTION,FN,
                "PKCS11 Certificate attributes creation failed");
            status = STATUS_ERROR_MAC_ENROLL_PDU;
                PR_snprintf(audit_msg, 512, "PKCS11 Certificate attributes creation failed");
           goto loser;
        }
    }

    if (pkcs11obj_enable) {
        RA::Debug(LL_PER_CONNECTION,FN,
          "Create PKCS11 Private Key Attributes Buffer");

        Buffer b;
        if (!isECC) {
            b = channel->CreatePKCS11PriKeyAttrsBuffer(key_type,
                        pri_attr_id, label, keyid, modulus, OP_PREFIX,
                        tokenType, keyTypePrefix);

        } else { //isECC
            eccParams  =   &pk_p->u.ec.DEREncodedParams;
            b = channel->CreatePKCS11ECCPriKeyAttrsBuffer(key_type,     
                        pri_attr_id, label, keyid, eccParams, OP_PREFIX,
                        tokenType, keyTypePrefix);
        }
        ObjectSpec *objSpec = 
                ObjectSpec::ParseFromTokenData( 
                                (pri_attr_id[0] << 24) +
                                (pri_attr_id[1] << 16),
                                &b);
        pkcs_objx->AddObjectSpec(objSpec);
    } else {
    	RA::Debug(LL_PER_CONNECTION,FN,
		"Create PKCS11 Private Key Attributes");
    	rc = channel->CreatePKCS11PriKeyAttrs(key_type, pri_attr_id, label, keyid, modulus, OP_PREFIX, tokenType, keyTypePrefix);
    	if (rc == -1) {
        	RA::Error(LL_PER_CONNECTION,FN,
		"PKCS11 private key attributes creation failed");
        	status = STATUS_ERROR_MAC_ENROLL_PDU;
                PR_snprintf(audit_msg, 512, "PKCS11 private key attributes creation failed");
        	goto loser;
    	}
    }

    if (pkcs11obj_enable) {
        Buffer b;
        if (!isECC) {
            b = channel->CreatePKCS11PubKeyAttrsBuffer(key_type, 
                pub_attr_id, label, keyid, 
                exponent, modulus, OP_PREFIX, tokenType, keyTypePrefix);
        } else {
            b = channel->CreatePKCS11ECCPubKeyAttrsBuffer(key_type,
                        pub_attr_id, label, keyid,&pk_p->u.ec, eccParams,
                        OP_PREFIX, tokenType, keyTypePrefix);
        }
        ObjectSpec *objSpec = 
            ObjectSpec::ParseFromTokenData(
               (pub_attr_id[0] << 24) +
               (pub_attr_id[1] << 16),
               &b);
        pkcs_objx->AddObjectSpec(objSpec);
    } else {
        RA::Debug(LL_PER_CONNECTION,FN,
            "Create PKCS11 Public Key Attributes");
        rc = channel->CreatePKCS11PubKeyAttrs(key_type, pub_attr_id, label, keyid, 
           exponent, modulus, OP_PREFIX, tokenType, keyTypePrefix);
        if (rc == -1) {
            RA::Error(LL_PER_CONNECTION,FN,
                "PKCS11 public key attributes creation failed");
            status = STATUS_ERROR_MAC_ENROLL_PDU;
                PR_snprintf(audit_msg, 512, "PKCS11 public key attributes creation failed");
            goto loser;
        }
    }
    RA::Debug(LL_PER_CONNECTION,FN, "End of keygen/certificate enrollment");

    PR_snprintf(activity_msg, 4096, "certificate %s stored on token", cert_serial);
    RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
      userid != NULL ? userid : "",
      cuid != NULL ? cuid : "",
      msn != NULL ? msn : "",
      "success",
      "enrollment",
      applet_version != NULL ? applet_version : "",
      keyVersion != NULL? keyVersion : "",
      activity_msg);
 
   RA::tdb_activity(session->GetRemoteIP(), 
      (char *) cuid, 
      "enrollment", 
      "success", 
      activity_msg,
      userid != NULL? userid : "",
      tokenType);

loser:
    if (strlen(audit_msg) > 0) { // a failure occurred
        RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
          userid != NULL ? userid : "",
          cuid != NULL ? cuid : "",
          msn != NULL ? msn : "",
          "failure",
          "enrollment",
          applet_version != NULL ? applet_version : "",
          keyVersion != NULL? keyVersion : "",
          audit_msg);

        if ((cuid != NULL) && (tokenType != NULL)) {
            RA::tdb_activity(session->GetRemoteIP(),
                (char *) cuid,
                "enrollment",
                "failure",
                audit_msg,
                userid != NULL? userid : "",
                tokenType);
        }
    }

    if( keyVersion != NULL ) {
        PR_Free( (char *) keyVersion );
        keyVersion = NULL;
    }

    if( modulus != NULL ) {
        delete modulus;
        modulus = NULL;
    }
    if( keyid != NULL ) {
        delete keyid;
        keyid = NULL;
    }
    if( exponent != NULL ) {
        delete exponent;
        exponent = NULL;
    }
    if( cert != NULL ) {
        delete cert;
        cert = NULL;
    }
    if( public_key != NULL ) {
        delete public_key;
        public_key = NULL;
    }
  
    if (pKey !=NULL)
        PR_Free(pKey);

    if (wrappedPrivKey !=NULL)
        PR_Free(wrappedPrivKey);

    if( si_kid != NULL ) {
        SECITEM_FreeItem( si_kid, PR_TRUE );
        si_kid = NULL;
    }
    if( certEnroll != NULL ) {
        delete certEnroll;
        certEnroll = NULL;
    }
    if( label != NULL ) {
        PL_strfree( (char *) label );
        label = NULL;
    }
    if( cuid_label != NULL ) {
        PL_strfree( (char *) cuid_label );
        cuid_label = NULL;
    }
    if( pretty_cuid != NULL ) {
        PR_Free( (char *) pretty_cuid );
        pretty_cuid = NULL;
    }
    if (pk_p != NULL) {
        if (serverKeygen) {
            RA::Debug(LL_PER_CONNECTION,FN,"DoEnrollment about to call SECKEY_DestroyPublicKey on pk_p");
            SECKEY_DestroyPublicKey(pk_p);
        } else {
            RA::Debug(LL_PER_CONNECTION,FN,"DoEnrollment about to call free on pk_p");
            free(pk_p);
        }

        pk_p = NULL;
    }
    return status;
}

SECStatus getRandomNumber(unsigned long *number) {
  SECStatus rv;

  if (number == NULL) {
    return SECFailure;
  }

  rv = PK11_GenerateRandom((unsigned char *) number, sizeof(unsigned long));
  return rv;
}


/**
 * @return true if successfull
 */
bool RA_Enroll_Processor::GetCardManagerAppletInfo(
    RA_Session *a_session,   /* in */
	Buffer *a_cardmanagerAID,  /* in */
    RA_Status &a_status,     /* out */
    char * &msn,             /* out */
    char * &cuid,            /* out */
    Buffer &token_cuid       /* out */
)
{
	bool r = true;  // result
    Buffer *cplc_data = NULL;
    Buffer token_msn;

    SelectApplet(a_session, 0x04, 0x00, a_cardmanagerAID);
    cplc_data = GetData(a_session);
    if (cplc_data == NULL) {
          RA::Error("RA_Enroll_Processor::Process", 
			"Get Data Failed");
          a_status = STATUS_ERROR_SECURE_CHANNEL;		 
		  r = false;
          goto loser;
    }
    RA::DebugBuffer("RA_Enroll_Processor::process", "CPLC Data = ", 
		    	cplc_data);
    if (cplc_data->size() < 47) {
          RA::Error("RA_Format_Processor::Process",
                        "Invalid CPLC Size");
          a_status = STATUS_ERROR_SECURE_CHANNEL;
		  r = false;
          goto loser;
    }
    token_cuid =  Buffer(cplc_data->substr(3,4)) + 
	     Buffer(cplc_data->substr(19,2)) + 
	     Buffer(cplc_data->substr(15,4));
    RA::DebugBuffer("RA_Enroll_Processor::process", "Token CUID= ", 
		    	&token_cuid);
    cuid = Util::Buffer2String(token_cuid);
    RA::Debug("RA_Enroll_Processor::process", "CUID(String)= '%s'", 
		    	cuid);
    token_msn = Buffer(cplc_data->substr(41, 4));
    RA::DebugBuffer("RA_Enroll_Processor::process", "Token MSN= ", 
		    	&token_msn);
    msn = Util::Buffer2String(token_msn);
    RA::Debug("RA_Enroll_Processor::process", "MSN(String)= '%s'", 
		    	msn);
	loser:
    if( cplc_data != NULL ) {
        delete cplc_data;
    }

	return r;
}

bool RA_Enroll_Processor::GetAppletInfo(
	RA_Session *a_session,   /* in */
    Buffer *a_aid ,  /* in */
    BYTE &o_major_version,
    BYTE &o_minor_version,
    BYTE &o_app_major_version,
    BYTE &o_app_minor_version)
{
    int total_mem = 0;
    int free_mem  = 0;
    Buffer *token_status = NULL;
    SelectApplet(a_session, 0x04, 0x00, a_aid);
    token_status = GetStatus(a_session, 0x00, 0x00);
    if (token_status == NULL) {
      o_major_version = 0x0;
      o_minor_version = 0x0;
      o_app_major_version = 0x0;
      o_app_minor_version = 0x0;
    } else {
      o_major_version = ((BYTE*)*token_status)[0];     // is this protocol version?
      o_minor_version = ((BYTE*)*token_status)[1];
      o_app_major_version = ((BYTE*)*token_status)[2]; // and this applet version?
      o_app_minor_version = ((BYTE*)*token_status)[3];

      BYTE tot_high = ((BYTE*)*token_status)[6];
      BYTE tot_low  = ((BYTE*)*token_status)[7];

      BYTE free_high = ((BYTE*)*token_status)[10];
      BYTE free_low  = ((BYTE*)*token_status)[11];

      total_mem =   (tot_high << 8)  + tot_low;
      free_mem  =   (free_high << 8) + free_low;

      totalAvailableMemory = total_mem;
      totalFreeMemory      = free_mem;

      RA::DebugBuffer("RA_Enroll_Processor::Process AppletInfo Data", "Data=", token_status);
      delete token_status;
    }
    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
	      "Major=%d Minor=%d Applet Major=%d Applet Minor=%d Total Mem %d Free Mem %d", 
			o_major_version, o_minor_version, o_app_major_version, o_app_minor_version,total_mem,free_mem);
	return true;
}


/**
 * Query applet for build ID info
 * 'Pretty'-print it into useful format, along with version info
 * example input:
 *  a_app_major_version = 1
 *  a_app_minor_version = 3
 * Examples for the following outputs:
 * o_av   = "1.3.45FC0218"
 * The caller is responsible for free'ing (o_av)
 */
bool RA_Enroll_Processor::FormatAppletVersionInfo(
    RA_Session *a_session,
	const char *a_tokenType,
	char *a_cuid,
    BYTE a_app_major_version,
    BYTE a_app_minor_version,
	RA_Status &o_status,            // out
	char * &o_av // out.  
)
{
	bool r=true;
	char configname[256];
	char *av=NULL;
	
	// retrieve the 4-byte applet ID from the token
	Buffer *tokenBuildID = GetAppletVersion(a_session);

	if (tokenBuildID == NULL) {
		// If there was no applet on the token
		PR_snprintf((char *)configname, 256, "%s.%s.update.applet.emptyToken.enable", OP_PREFIX,
				a_tokenType);
	// XXX checks if emptyToken is enabled. This should probably get moved
    // to the applet update function, and leave this fn only for getting
    // the version information
		if (!RA::GetConfigStore()->GetConfigAsBool(configname, 0)) {
			RA::Error("RA_Enroll_Processor::Process", 
					"no applet found and applet upgrade not enabled");
			o_status = STATUS_ERROR_SECURE_CHANNEL;  // XXX  incorrect error message
			r=false;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "secure channel not established", "", a_tokenType); // XXX incorrect error message
			goto loser;
		}
	} else {
		// if there was an applet on the token:
		char * bid_string =  Util::Buffer2String(*tokenBuildID);
		RA::Debug("RA_Enroll_Processor", "buildid = %s", bid_string);
		av = PR_smprintf( "%x.%x.%s", 
			a_app_major_version, a_app_minor_version, bid_string);
		PR_Free(bid_string);
	}
	o_av = (av == NULL) ? strdup("") : av;

	RA::Debug("RA_Enroll_Processor", "final_applet_version = %s", o_av);
loser:
	if( tokenBuildID != NULL ) {
		delete tokenBuildID;
	}
	return r;
}

/**
 * Checks if we need to upgrade applet. 
 * The version of the current token is passed IN to this function
 * in o_current_applet_on_token. If the applet is upgraded, this
 * out parameter will be set to the new applet version id.
 * maj/minor versions will be also updated if the applet was updated.
 */
bool RA_Enroll_Processor::CheckAndUpgradeApplet(
		RA_Session *a_session,
		NameValueSet *a_extensions,
		char *a_cuid,
		const char *a_tokenType,
		char *&o_current_applet_on_token,
		BYTE &o_major_version,
		BYTE &o_minor_version,
		Buffer *a_aid,
                const char *a_msn, 
                const char *a_userid,
		RA_Status &o_status, 
                char **keyVersion )
{
        int rc = 0;
	const char *FN = "RA_Enroll_Processor::CheckAndUpgradeApplet";
	bool r = true;
	const char *applet_dir=NULL;
    const char *connid = NULL;
    Buffer *token_status = NULL;
	char configname[256];

	// You specify the following parameters to get applet upgrade working
	// *.update.applet.enable=true
	// *.update.applet.requiredVersion=maj.min.xxxxxxxx
	PR_snprintf((char *)configname, 256, "%s.%s.update.applet.encryption", OP_PREFIX, a_tokenType);
	SecurityLevel security_level = SECURE_MSG_MAC;
	if (RA::GetConfigStore()->GetConfigAsBool(configname, true))
			security_level = SECURE_MSG_MAC_ENC;

    PR_snprintf((char *)configname, 256, "%s.%s.update.applet.enable", OP_PREFIX, a_tokenType);
	if (RA::GetConfigStore()->GetConfigAsBool(configname, 0)) {
		PR_snprintf((char *)configname, 256, "%s.%s.update.applet.requiredVersion", OP_PREFIX, a_tokenType);
                g_applet_target_version = RA::GetConfigStore()->GetConfigAsString(configname);
		if (g_applet_target_version == NULL) {
			RA::Error(FN, "upgrade.version not found");
			o_status = STATUS_ERROR_MISCONFIGURATION;		 
			r = false;
			goto loser;
		}
		/* Bugscape #55826: used case-insensitive check below */
		if (PL_strcasecmp(g_applet_target_version, o_current_applet_on_token) != 0) {
			RA::Debug(LL_PER_CONNECTION, FN, "tokenType=%s before updating applet", a_tokenType);
			/* upgrade applet */
			PR_snprintf((char *)configname, 256, "%s.%s.update.applet.directory", OP_PREFIX, a_tokenType);
			applet_dir = RA::GetConfigStore()->GetConfigAsString(configname);
			if (applet_dir == NULL || strlen(applet_dir) == 0) {
				RA::Error(LL_PER_CONNECTION, FN,
						"Failed to read applet directory parameter %s", configname);
				o_status = STATUS_ERROR_MISCONFIGURATION;		 
				r = false;
				goto loser;
			}
			PR_snprintf((char *)configname, 256, "%s.%s.tks.conn", OP_PREFIX, a_tokenType);
			connid = RA::GetConfigStore()->GetConfigAsString(configname);
			RA::Debug(FN, "TKS connection id =%s", connid);
			//StatusUpdate(a_session, a_extensions, 5, "PROGRESS_UPGRADE_APPLET");

			if (rc = UpgradeApplet(a_session, (char *) OP_PREFIX, (char*) a_tokenType,
				o_major_version, o_minor_version, 
				g_applet_target_version, 
				applet_dir, security_level, 
				connid, a_extensions, 
				5, 
				12, 
                                keyVersion) != 1) {

				RA::Debug(FN, "applet upgrade failed");
				/**
				 * Bugscape #55709: Re-select Net Key Applet ONLY on failure.
				 */
				SelectApplet(a_session, 0x04, 0x00, a_aid);
				RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "applet upgrade error", "", a_tokenType);
				o_status = STATUS_ERROR_UPGRADE_APPLET;		 
				r = false;

                                if (rc == -1) {
                                    RA::Audit(EV_APPLET_UPGRADE, AUDIT_MSG_APPLET_UPGRADE,
                                        a_userid, a_cuid, a_msn, "Failure", "enrollment",
                                        *keyVersion != NULL? *keyVersion : "", o_current_applet_on_token, g_applet_target_version, "failed to setup secure channel");
                                } else {

                                    RA::Audit(EV_APPLET_UPGRADE, AUDIT_MSG_APPLET_UPGRADE,
                                    a_userid, a_cuid, a_msn, "Success", "enrollment",
                                    *keyVersion != NULL? *keyVersion : "", o_current_applet_on_token, g_applet_target_version, "setup secure channel");
                                }


                                RA::Audit(EV_APPLET_UPGRADE, AUDIT_MSG_APPLET_UPGRADE,
                                  a_userid, a_cuid, a_msn, "Failure", "enrollment",
                                  *keyVersion != NULL? *keyVersion : "",
                                  o_current_applet_on_token, g_applet_target_version,
                                  "applet upgrade");
                                
				goto loser;
			} else {
				// there may be a better place to do this, but worth testing here
				// RA::tdb_update(a_cuid, g_applet_target_version);
			}

			// Upgrade Applet reported success
			
                        RA::Audit(EV_APPLET_UPGRADE, AUDIT_MSG_APPLET_UPGRADE,
                            a_userid, a_cuid, a_msn, "Success", "enrollment",
                            *keyVersion != NULL? *keyVersion : "", o_current_applet_on_token, g_applet_target_version, "setup secure channel");

                        RA::Audit(EV_APPLET_UPGRADE, AUDIT_MSG_APPLET_UPGRADE,
                          a_userid, a_cuid, a_msn, "Success", "enrollment",
                          *keyVersion != NULL? *keyVersion : "",
                          o_current_applet_on_token, g_applet_target_version, 
                          "applet upgrade");

			o_current_applet_on_token = strdup(g_applet_target_version);

			token_status = GetStatus(a_session, 0x00, 0x00);
			if (token_status == NULL) {
				RA::Error(FN, "Get Status Failed");
				o_status = STATUS_ERROR_SECURE_CHANNEL;		 // XXX
				RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "secure channel error", "", a_tokenType);
				r = false;
				goto loser;
			}

			o_major_version = ((BYTE*)*token_status)[2]; // applet version
			o_minor_version = ((BYTE*)*token_status)[3]; // not protocol version
loser:
    		if( token_status != NULL ) {
        		delete token_status;
    		}
		}
	} else {
        RA::Debug(FN, "Applet Upgrade has been disabled.");
    }
	return r;
}

/**
 * Authenticate user with LDAP plugin
 * @return true if authentication was successful
 */
bool RA_Enroll_Processor::AuthenticateUserLDAP(
		RA_Session *a_session,
                NameValueSet *a_extensions,
		char *a_cuid,
		AuthenticationEntry *a_auth,
		AuthParams *&login,
		RA_Status &o_status,
                const char *a_token_type
)
{
	const char *FN = "RA_Enroll_Processor::AuthenticateUserLDAP";
	int retry_limit = a_auth->GetAuthentication()->GetNumOfRetries();
	int retries = 0;
	int rc;
	bool r=false;

	RA::Debug(LL_PER_PDU, FN, "LDAP_Authentication is invoked.");
	rc = a_auth->GetAuthentication()->Authenticate(login);

	RA::Debug(FN, "Authenticate returned: %d", rc);

	// rc: (0:login correct) (-1:LDAP error)  (-2:User not found) (-3:Password error)

	// XXX replace with proper enums
	// XXX evaluate rc==0 as specific case - this is success, it shouldn't be the default

	while ((rc == TPS_AUTH_ERROR_USERNOTFOUND || 
			rc == TPS_AUTH_ERROR_PASSWORDINCORRECT ) 
				&& (retries < retry_limit)) {
		login = RequestLogin(a_session, 0 /* invalid_pw */, 0 /* blocked */);
		retries++;
        if (login != NULL)
		    rc = a_auth->GetAuthentication()->Authenticate(login);
	}

	switch (rc) {
	case TPS_AUTH_OK:
		RA::Debug(LL_PER_PDU, FN, "Authentication successful.");
		r=true;
		break;
	case TPS_AUTH_ERROR_LDAP:
		RA::Error(FN, "Authentication failed. LDAP Error");
		o_status = STATUS_ERROR_LDAP_CONN;
		RA::Debug(LL_PER_PDU, FN, "Authentication status=%d rc=%d", o_status,rc);
		RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "authentication error", "", a_token_type);
		r = false;
		break;
	case TPS_AUTH_ERROR_USERNOTFOUND:
		RA::Error(FN, "Authentication failed. User not found");
		o_status = STATUS_ERROR_LOGIN;
		RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "authentication error",  "", a_token_type);
		r = false;
		break;
	case TPS_AUTH_ERROR_PASSWORDINCORRECT:
		RA::Error(FN, "Authentication failed. Password Incorrect");
		o_status = STATUS_ERROR_LOGIN;
		RA::Debug(LL_PER_PDU, FN, "Authentication status=%d rc=%d", o_status,rc);
		RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "authentication error", "", a_token_type);
		r = false;
		break;
	default:
		RA::Error(FN, "Undefined LDAP Auth Error.");
		r = false;
		break;
	}

	return r;
}

/**
 * Request Login info and user id from user, if necessary
 * This call will allocate a new Login structure,
 * and a char* for the user id. The caller is responsible
 * for freeing this memory
 * @return true of success, false if failure
 */
bool RA_Enroll_Processor::RequestUserId(
			RA_Session * a_session,
                        NameValueSet *a_extensions,
			const char * a_configname, 
			const char * a_tokenType, 
			char *a_cuid,
			AuthParams *& o_login, const char *&o_userid, RA_Status &o_status) 
{

	if (RA::GetConfigStore()->GetConfigAsBool(a_configname, 1)) {
		if (a_extensions != NULL && 
		    a_extensions->GetValue("extendedLoginRequest") != NULL) 
                {
                   // XXX - extendedLoginRequest
                   RA::Debug("RA_Enroll_Processor::RequestUserId",
				"Extended Login Request detected");
                   AuthenticationEntry *entry = GetAuthenticationEntry(
			OP_PREFIX, a_configname, a_tokenType);
                   char **params = NULL;
                   char pb[1024];
                   char *locale = NULL;
		   if (a_extensions != NULL && 
		       a_extensions->GetValue("locale") != NULL) 
                   {
                           locale = a_extensions->GetValue("locale");
                   } else {
                           locale = ( char * ) "en"; /* default to english */
                   }
                   int n = entry->GetAuthentication()->GetNumOfParamNames();
                   if (n > 0) {
                       RA::Debug("RA_Enroll_Processor::RequestUserId",
				"Extended Login Request detected n=%d", n);
                       params = (char **) PR_Malloc(n);
                       for (int i = 0; i < n; i++) {
                         sprintf(pb,"id=%s&name=%s&desc=%s&type=%s&option=%s",
                             entry->GetAuthentication()->GetParamID(i),
                             entry->GetAuthentication()->GetParamName(i, locale),
                             entry->GetAuthentication()->GetParamDescription(i, locale),
                             entry->GetAuthentication()->GetParamType(i),
                             entry->GetAuthentication()->GetParamOption(i)
                             );
                         params[i] = PL_strdup(pb);
                   RA::Debug("RA_Enroll_Processor::RequestUserId", 
				"params[i]=%s", params[i]);
                       }
                   }
                   RA::Debug("RA_Enroll_Processor::RequestUserId", "Extended Login Request detected calling RequestExtendedLogin() locale=%s", locale);

                   char *title = PL_strdup(entry->GetAuthentication()->GetTitle(locale));
                   RA::Debug("RA_Enroll_Processor::RequestUserId", "title=%s", title);
                   char *description = PL_strdup(entry->GetAuthentication()->GetDescription(locale));
                   RA::Debug("RA_Enroll_Processor::RequestUserId", "description=%s", description);
		   o_login = RequestExtendedLogin(a_session, 0 /* invalid_pw */, 0 /* blocked */, params, n, title, description);

                   if (params != NULL) {
                       for (int nn=0; nn < n; nn++) {
                           if (params[nn] != NULL) {
                               PL_strfree(params[nn]);
                               params[nn] = NULL;
                           }
                       }
                       free(params);
                       params = NULL;
                   }

                   if (title != NULL) {
                       PL_strfree(title);
                       title = NULL;
                   }

                   if (description != NULL) {
                       PL_strfree(description);
                       description = NULL;
                   }

		  if (o_login == NULL) {
			RA::Error("RA_Enroll_Processor::Process", 
					"login not provided");
			o_status = STATUS_ERROR_LOGIN;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, 
					"enrollment", "failure", "login not found", "", a_tokenType);
			return false;
		  }

                   RA::Debug("RA_Enroll_Processor::RequestUserId",
	"Extended Login Request detected calling RequestExtendedLogin() login=%x", o_login);
		  o_userid = PL_strdup( o_login->GetUID() );
		  RA::Debug("RA_Enroll_Processor::Process", 
				"userid = '%s'", o_userid);
                } else {
		  o_login = RequestLogin(a_session, 0 /* invalid_pw */, 0 /* blocked */);
		  if (o_login == NULL) {
			RA::Error("RA_Enroll_Processor::Process", 
					"login not provided");
			o_status = STATUS_ERROR_LOGIN;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, 
					"enrollment", "failure", "login not found", o_userid, a_tokenType);
			return false;
		  }
		  o_userid = PL_strdup( o_login->GetUID() );
		  RA::Debug("RA_Enroll_Processor::Process", 
				"userid = '%s'", o_userid);
                }
	}
	return true;
}

/**
 *  Authenticate the user with the configured authentication plugin
 * @return true if authentication successful
 */

bool RA_Enroll_Processor::AuthenticateUser(
			RA_Session * a_session,
			const char * a_configname, 
			char *a_cuid,
			NameValueSet *a_extensions,
			const char *a_tokenType,
			AuthParams *& a_login, const char *&o_userid, RA_Status &o_status
			)
{
	bool r=false;

	RA::Debug("RA_Enroll_Processor::AuthenticateUser", "started");
	if (RA::GetConfigStore()->GetConfigAsBool(a_configname, false)) {
		if (a_login == NULL) {
			RA::Error("RA_Enroll_Processor::AuthenticateUser", "Login Request Disabled. Authentication failed.");
			o_status = STATUS_ERROR_LOGIN;
			goto loser;
		}

		RA::Debug("RA_Enroll_Processor::AuthenticateUser",
				"Authentication enabled");
		char configname[256];
		PR_snprintf((char *)configname, 256, "%s.%s.auth.id", OP_PREFIX, a_tokenType);
		const char *authid = RA::GetConfigStore()->GetConfigAsString(configname);
		if (authid == NULL) {
			o_status = STATUS_ERROR_LOGIN;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "login not found", "", a_tokenType);
			goto loser;
		}
		AuthenticationEntry *auth = RA::GetAuth(authid);

		if (auth == NULL) {
			o_status = STATUS_ERROR_LOGIN;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "authentication error", "", a_tokenType);
			goto loser;
		}

		StatusUpdate(a_session, a_extensions, 2, "PROGRESS_START_AUTHENTICATION");

		char *type = auth->GetType();
		if (type == NULL) {
			o_status = STATUS_ERROR_LOGIN;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "authentication is missing param type", "", a_tokenType);
			r = false;
			goto loser;
		}

		if (strcmp(type, "LDAP_Authentication") == 0) {
	                RA::Debug("RA_Enroll_Processor::AuthenticateUser", "LDAP started");
			r = AuthenticateUserLDAP(a_session, a_extensions, a_cuid, auth, a_login, o_status, a_tokenType);
			o_status = STATUS_ERROR_LOGIN;
			goto loser;
		} else {
			RA::Error("RA_Enroll_Processor::AuthenticateUser", "No Authentication type was found.");
			o_status = STATUS_ERROR_LOGIN;
			RA::tdb_activity(a_session->GetRemoteIP(), a_cuid, "enrollment", "failure", "authentication error", "", a_tokenType);
			r = false;
			goto loser;
		}
	} else {
		r = true;
		RA::Debug("RA_Enroll_Processor::AuthenticateUser",
				"Authentication has been disabled.");
	}
	loser:
		return r;
}




    /**
     * Checks if the token has the required key version.
	 * If not, we can swap out the keys on the token with another
     * set of keys
     */

/* XXX AID's should be member variables */
bool RA_Enroll_Processor::CheckAndUpgradeSymKeys(
	//RA_Session * a_session,
	//NameValueSet *a_extensions,
	//const char * a_configname, 
	//char *a_cuid,
	RA_Session *a_session,
	NameValueSet* a_extensions,
	char *a_cuid,
	const char *a_tokenType,
	char *a_msn,
        const char *a_applet_version,
        const char *a_userid,
        const char *a_key_version,
	Buffer *a_cardmanagerAID,  /* in */
	Buffer *a_appletAID,       /* in */
    Secure_Channel *&o_channel,  /* out */
	RA_Status &o_status          /* out */
	)
{
	char *FN = ( char * ) "RA_EnrollProcessor::CheckAndUpgradeSymKeys";
	char configname[256];
	const char *connid = NULL;
	const char *tksid = NULL;
	int rc;
	bool r = false;
	Buffer key_data_set;
        char audit_msg[512] = "";
        char curVer[10];
        char newVer[10];

        char *curKeyInfoStr = NULL;
        char *newVersionStr = NULL;

	// the TKS is responsible for doing much of the symmetric keys update
	// so lets find which TKS we're talking about TKS now.
	PR_snprintf((char *)configname, 256, "%s.%s.tks.conn", OP_PREFIX, a_tokenType);
	tksid = RA::GetConfigStore()->GetConfigAsString(configname);

	PR_snprintf((char *)configname, 256,"%s.%s.update.symmetricKeys.enable", OP_PREFIX, a_tokenType);

	RA::Debug(FN, "Symmetric Keys %s", configname);

	if (RA::GetConfigStore()->GetConfigAsBool(configname, 0)) {

		RA::Debug(LL_PER_CONNECTION, FN, 
			"tokenType=%s configured to update symmetric keys", a_tokenType);

		// the requiredVersion config parameter indicates what key version
		// the token should have before further operations. If the token
		// has an older version, we try to change it.
		PR_snprintf((char *)configname, 256, 
			"%s.%s.update.symmetricKeys.requiredVersion", OP_PREFIX, a_tokenType);

		int requiredV = RA::GetConfigStore()->GetConfigAsInt(configname, 0x00);

		// If there was a secure channel set up, let's clear it out
		if( o_channel != NULL ) {
			delete o_channel;
			o_channel = NULL;
		}
		// try to make a secure channel with the 'requiredVersion' keys
		// If this fails, we know we will have to attempt an upgrade
		// of the keys
        PR_snprintf((char *)configname, 256,"channel.defKeyIndex");
        int defKeyIndex = RA::GetConfigStore()->GetConfigAsInt(configname, 0x0);
		o_channel = SetupSecureChannel(a_session, 
				requiredV,
				defKeyIndex  /* default key index */, tksid);

		// If that failed, we need to find out what version of keys 
		// are on the token
		if (o_channel != NULL) {
          r = true;
        } else {
			/**
			 * Select Card Manager for Put Key operation.
			 */
			SelectApplet(a_session, 0x04, 0x00, a_cardmanagerAID);
			/* if the key of the required version is
			 * not found, create them.
			 */ 
			//  This sends a InitializeUpdate request to the token.
			//  We tell the token to use whatever it thinks is the
			//  default key version (0). It will return the version
			//  of the key it actually used later. (This is accessed
			//  with GetKeyInfoData below)
			//  [ Note: This is not explained very well in the manual
			//    The token can have multiple sets of symmetric keys
			//    Each set is given a version number, which I think is
			//    better thought of as a SLOT. One key slot is populated
			//    with a set of keys when the token is manufactured.
			//    This is then designated as the default key set version.
			//    Later, we will write a new key set with PutKey, and
			//    set it to be the new default]
        PR_snprintf((char *)configname, 256,"channel.defKeyVersion");
        int defKeyVer = RA::GetConfigStore()->GetConfigAsInt(configname, 0x0);
        PR_snprintf((char *)configname, 256,"channel.defKeyIndex");
        int defKeyIndex = RA::GetConfigStore()->GetConfigAsInt(configname, 0x0);
			o_channel = SetupSecureChannel(a_session, 
					defKeyVer,  /* default key version */
					defKeyIndex  /* default key index */, tksid);

			if (o_channel == NULL) {
                                PR_snprintf(audit_msg, 512, "enrollment processing, failed to create secure channel"); 

				RA::Error(FN, "failed to establish secure channel");
				o_status = STATUS_ERROR_SECURE_CHANNEL;		 
				goto loser;
			}

			/* Complete the secure channel handshake */
			/* XXX need real enumeration of error codes here */
			rc = o_channel->ExternalAuthenticate();
			if (rc != 1) {
				RA::Error(FN, "External authentication in secure channel failed");
				o_status = STATUS_ERROR_EXTERNAL_AUTH;
				/* XXX should print out error codes */
                                PR_snprintf(audit_msg, 512, "enrollment processing, external authentication error"); 
				goto loser;
			}

			// Assemble the Buffer with the version information
			// The second byte is the key offset, which is always 1
			BYTE nv[2] = { requiredV, 0x01 };
			Buffer newVersion(nv, 2);

			// GetKeyInfoData will return a buffer which is bytes 11,12 of
			// the data structure on page 89 of Cyberflex Access Programmer's
			// Guide
			// Byte 0 is the key set version.
			// Byte 1 is the index into that key set
			Buffer curKeyInfo = o_channel->GetKeyInfoData();


			// This code makes a call to the TKS to get a new key set for
			// the token. The new key set data is written to the Buffer
			// key_data_set.
			PR_snprintf((char *)configname, 256,"%s.%s.tks.conn", OP_PREFIX, a_tokenType);
			connid = RA::GetConfigStore()->GetConfigAsString(configname);

			rc = CreateKeySetData(
					o_channel->GetKeyDiversificationData(), 
					curKeyInfo,
					newVersion,
					key_data_set, connid);
			if (rc != 1) {
				RA::Error(FN, "failed to create new key set");
				o_status = STATUS_ERROR_CREATE_CARDMGR;
                                PR_snprintf(audit_msg, 512, "enrollment processing, create card key error"); 
				goto loser;
			}

			StatusUpdate(a_session, a_extensions, 13, "PROGRESS_PUT_KEY");

			// sends a PutKey PDU with the new key set to change the
			// keys on the token
			BYTE curVersion = ((BYTE*)curKeyInfo)[0];
			BYTE curIndex = ((BYTE*)curKeyInfo)[1];
			rc = o_channel->PutKeys(a_session, 
					curVersion, 
					curIndex,
					&key_data_set);


                        curKeyInfoStr = Util::Buffer2String(curKeyInfo);
                        newVersionStr = Util::Buffer2String(newVersion);

                        if(curKeyInfoStr != NULL && strlen(curKeyInfoStr) >= 2) {
                            curVer[0] = curKeyInfoStr[0]; curVer[1] = curKeyInfoStr[1]; curVer[2] = 0;
                        }
                        else {
                            curVer[0] = 0;
                        }

                        if(newVersionStr != NULL && strlen(newVersionStr) >= 2) {
                            newVer[0] = newVersionStr[0] ; newVer[1] = newVersionStr[1] ; newVer[2] = 0;
                        }
                        else {
                            newVer[0] = 0;
                        }


                        if (rc!=0) {
                            RA::Audit(EV_KEY_CHANGEOVER, AUDIT_MSG_KEY_CHANGEOVER,
                              a_userid != NULL ? a_userid : "", a_cuid != NULL ? a_cuid : "",  a_msn != NULL ? a_msn : "", "Failure", "enrollment",
                              a_applet_version != NULL ? a_applet_version : "", curVer, newVer,
                              "key changeover");

                            if ((a_cuid != NULL) && (a_tokenType != NULL)) {
                                RA::tdb_activity(a_session->GetRemoteIP(),
                                    a_cuid,
                                    "enrollment",
                                    "failure",
                                    "key changeover failed",
                                    a_userid != NULL? a_userid : "",
                                    a_tokenType);
                            }
                            goto loser;
                        } else {
                            RA::Audit(EV_KEY_CHANGEOVER, AUDIT_MSG_KEY_CHANGEOVER,
                              a_userid != NULL ? a_userid : "", a_cuid != NULL ? a_cuid : "", a_msn != NULL ? a_msn : "", "Success", "enrollment",
                              a_applet_version != NULL ? a_applet_version : "", curVer, newVer,
                              "key changeover");
                        }

			/**
			 * Re-select the Applet.
			 */
			SelectApplet(a_session, 0x04, 0x00, a_appletAID);
			if( o_channel != NULL ) {
				delete o_channel;
				o_channel = NULL;
			}

			// Make a new secure channel with the new symmetric keys
			o_channel = SetupSecureChannel(a_session, requiredV,
					defKeyIndex  /* default key index */, tksid);
			if (o_channel == NULL) {
				RA::Error(FN, "failed to establish secure channel after reselect");
				o_status = STATUS_ERROR_CREATE_CARDMGR;
                                PR_snprintf(audit_msg, 512, "enrollment processing, secure channel setup error after reselect"); 
				goto loser;
			} else {
				RA::Debug(FN, "Key Upgrade has completed successfully.");
				r = true;  // Success!!

                                RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
                                  a_userid != NULL ? a_userid : "", a_cuid != NULL ? a_cuid : "", 
                                  a_msn != NULL ? a_msn : "", "success", "enrollment", a_applet_version != NULL ? a_applet_version : "",
                                  newVer, "enrollment processing, key upgrade completed");
			}

		}
	} else {

		RA::Debug(FN, "Key Upgrade has been disabled.");

		if( o_channel != NULL ) {
			delete o_channel;
			o_channel = NULL;
		}
        PR_snprintf((char *)configname, 256,"channel.defKeyVersion");
        int defKeyVer = RA::GetConfigStore()->GetConfigAsInt(configname, 0x0);
        PR_snprintf((char *)configname, 256,"channel.defKeyIndex");
        int defKeyIndex = RA::GetConfigStore()->GetConfigAsInt(configname, 0x0);
		o_channel = SetupSecureChannel(a_session, 
				defKeyVer,
				defKeyIndex  /* default key index */, tksid);
		r = true;	  // Sucess!!
                RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
                  a_userid, a_cuid, a_msn, "success", "enrollment", a_applet_version, 
                  a_key_version != NULL? a_key_version: "", 
                  "enrollment processing, key upgrade disabled");
	}
loser:
    
    if (curKeyInfoStr != NULL) {
        PR_Free( (char *) curKeyInfoStr);
        curKeyInfoStr = NULL;
    }

    if (newVersionStr != NULL) {
        PR_Free( (char *) newVersionStr);
        newVersionStr = NULL;
    }

    if (strlen(audit_msg) > 0) { // a failure occurred
        RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
          a_userid != NULL ? a_userid : "",
          a_cuid != NULL ? a_cuid : "",
          a_msn != NULL ? a_msn : "",
          "failure",
          "enrollment",
          a_applet_version != NULL ? a_applet_version : "",
          a_key_version != NULL? a_key_version : "", 
          audit_msg);

        if ((a_cuid != NULL) && (a_tokenType != NULL)) {
            RA::tdb_activity(a_session->GetRemoteIP(),
                a_cuid,
                "enrollment",
                "failure",
                audit_msg,
                a_userid != NULL? a_userid : "",
                a_tokenType);
        }
    }

    return r;
}

/**
 * Processes the current session.
 */
TPS_PUBLIC RA_Status RA_Enroll_Processor::Process(RA_Session *session, NameValueSet *extensions)
{
    char *FN = ( char * ) "RA_Enroll_Processor::Process";
    char configname[256];
    char *cuid = NULL;
    char *msn = NULL;
    PRIntervalTime start, end;
    RA_Status status = STATUS_NO_ERROR;
    int rc = -1;
    Secure_Channel *channel = NULL;
    Buffer kdd;
    AuthParams *login = NULL;
    char *new_pin = NULL;
#define PLAINTEXT_CHALLENGE_SIZE 16
#define WRAPPED_CHALLENGE_SIZE 16
    Buffer *plaintext_challenge = 
        new Buffer(PLAINTEXT_CHALLENGE_SIZE, (BYTE)0);
    Buffer *wrapped_challenge = new Buffer(WRAPPED_CHALLENGE_SIZE, (BYTE)0);
    Buffer *key_check = new Buffer(0, (BYTE)0);
    const char *tokenType = NULL;

    //SecurityLevel security_level = SECURE_MSG_MAC_ENC;
    BYTE major_version = 0x0;
    BYTE minor_version = 0x0;
    BYTE app_major_version = 0x0;
    BYTE app_minor_version = 0x0;
    int isPinPresent = 0;
    Buffer *object = NULL;
    int seq = 0x00;
    unsigned long lastFormatVersion = 0x00;
    unsigned long lastObjectVersion = 0x00;
    int foundLastObjectVersion = 0;
    int pkcs11obj_enable = 0;
    int compress = 0;
    NameValueSet nv;
    int o_certNums = 0;

    CertEnroll *certEnroll = NULL;

    Buffer *token_status = NULL;
    char* appletVersion = NULL;
    char *final_applet_version = NULL;

    char *keyVersion = PL_strdup( "" );
    const char *userid = PL_strdup( "" );
    char *token_state = PL_strdup("inactive");
    char *khex = NULL;

    Buffer host_challenge = Buffer(8, (BYTE)0);
    Buffer key_diversification_data;
    Buffer key_info_data;
    Buffer card_challenge;
    Buffer card_cryptogram;
    const char *connid = NULL;
    const char *tksid = NULL;
    const char *authid = NULL;
    PKCS11Obj *pkcs11objx = NULL;
    Buffer labelBuffer;
    char activity_msg[4096];
    char audit_msg[512] = ""; 

    Buffer *CardManagerAID = RA::GetConfigStore()->GetConfigAsBuffer(
		   RA::CFG_APPLET_CARDMGR_INSTANCE_AID, 
		   RA::CFG_DEF_CARDMGR_INSTANCE_AID);
    Buffer *NetKeyAID = RA::GetConfigStore()->GetConfigAsBuffer(
		    RA::CFG_APPLET_NETKEY_INSTANCE_AID, 
		    RA::CFG_DEF_NETKEY_INSTANCE_AID);
    Buffer token_cuid;
    int maxRetries = 3;
    const char *pattern = NULL;
    char *label = NULL;
    CERTCertificate **certificates = NULL;
    char **ktypes = NULL;
    char **origins = NULL;
    char **tokenTypes = NULL;
    char *tokentype = NULL;
    char *profile_state = NULL;
	RA_Status st;
    bool renewed = false;
    bool do_force_format = false;

    RA::Debug("RA_Enroll_Processor::Process", "Client %s", 
                      session->GetRemoteIP());
    RA::Debug(LL_PER_PDU, FN, "Begin enroll process");

    // XXX need to validate all user input (convert to 'string' types)
    // to ensure that no buffer overruns
    start = PR_IntervalNow();

    /* Get the card serial number */
    if (!GetCardManagerAppletInfo(session, CardManagerAID, st, msn, cuid, token_cuid)) goto loser;

    /* Get the applet version information */
    if (!GetAppletInfo(session, NetKeyAID, 
        /*by ref*/ major_version, minor_version, 
        app_major_version, app_minor_version )) goto loser;

    if (!GetTokenType(OP_PREFIX, major_version, minor_version, 
            cuid, msn, extensions,
            status, tokenType)) { /* last two are 'out' params */
        /* ADE figure out what to do here for this line*/
        // RA::tdb_activity(session->GetRemoteIP(), cuid, "enrollment", "failure", "token type not found", "");
        goto loser;
    }

    // check if profile is enabled here
    PR_snprintf((char *)configname, 256, "config.Profiles.%s.state", tokenType);
    profile_state = (char *) RA::GetConfigStore()->GetConfigAsString(configname);
    if ((profile_state != NULL) && (PL_strcmp(profile_state, "Enabled") != 0)) {
         RA::Error(FN, "Profile %s Disabled for CUID %s", tokenType, cuid);
         status =  STATUS_ERROR_DEFAULT_TOKENTYPE_PARAMS_NOT_FOUND;
         PR_snprintf(audit_msg, 512, "profile %s disabled", tokenType);
         goto loser;
    }

    if (RA::ra_is_token_present(cuid)) {

        int token_status = RA::ra_get_token_status(cuid);

         // As far as the ui states, state "enrolled" maps to the state of "FOUND" or 4;

         RA::Debug(FN, "Found token %s status %d", cuid, token_status);

        int STATUS_FOUND = 4;
        if (token_status == -1 || !RA::transition_allowed(token_status, STATUS_FOUND)) {
            RA::Error(FN, "Operation for CUID %s Disabled illegal transition attempted %d:%d", cuid,token_status, STATUS_FOUND);
            status = STATUS_ERROR_DISABLED_TOKEN;

            PR_snprintf(audit_msg, 512, "Operation for CUID %s Disabled, illegal transition attempted %d:%d.", cuid,token_status, STATUS_FOUND);
            goto loser;
        }

        // at this point, token is either active or uninitialized (formatted)
        // or the adminstrator has called for a force format.

        do_force_format = RA::ra_force_token_format(cuid);

        RA::Debug("RA_Enroll_Processor::Process","force format flag %d", do_force_format);

        if (!RA::ra_allow_token_reenroll(cuid) &&
            !RA::ra_allow_token_renew(cuid) &&
            !do_force_format) {
            RA::Error(FN, "CUID %s Re-Enrolled Disallowed", cuid);
            status = STATUS_ERROR_DISABLED_TOKEN;
            PR_snprintf(audit_msg, 512, "token re-enrollment or renewal disallowed");
            goto loser;
        }
    } else {
        RA::Debug(FN, "Not Found token %s", cuid);
        // This is a new token. We need to check our policy to see
        // if we should allow enrollment. raidzilla #57414
        PR_snprintf((char *)configname, 256, "%s.allowUnknownToken", 
            OP_PREFIX);
        if (!RA::GetConfigStore()->GetConfigAsBool(configname, 1)) {
            RA::Error(FN, "CUID %s Enroll Unknown Token", cuid);
            status = STATUS_ERROR_DISABLED_TOKEN;
            PR_snprintf(audit_msg, 512, "unknown token disallowed");
            goto loser;
        }
    }

    RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
        userid != NULL ? userid : "",
        cuid != NULL ? cuid : "",
        msn != NULL ? msn : "",
        "success",
        "enrollment",
        final_applet_version != NULL ? final_applet_version : "",
        keyVersion != NULL ? keyVersion : "",
        "token enabled");


    /* XXX - this comment does not belong here
     *
     * This is very risky to call initialize and then
     * external authenticate later on.
     * The token will be locked if no external authenticate
     * follows the initialize update.
     */

    PR_snprintf((char *)configname, 256, "%s.%s.tks.conn", 
		    OP_PREFIX, tokenType);
    tksid = RA::GetConfigStore()->GetConfigAsString(configname);
    if (tksid == NULL) {
        RA::Error(FN, "TKS Connection Parameter %s Not Found", configname);
        status = STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND;
        PR_snprintf(audit_msg, 512, "token type TKS connection parameter not found");
        goto loser;
    }

	/* figure some more information about the applet version */
	/* XXX should probably move this further down, since the results
       of this function aren't used til much later */
	if (!FormatAppletVersionInfo(session, tokenType, cuid,
		app_major_version, app_minor_version,
		status,
		final_applet_version /*out */)) { 
            PR_snprintf(audit_msg, 512, "FormatAppletVersionInfo error");
            goto loser;
        }

	PR_snprintf((char *)configname, 256, "%s.%s.loginRequest.enable", OP_PREFIX, tokenType);
	if (!RequestUserId(session, extensions, configname, tokenType, cuid, login, userid, status)){
                PR_snprintf(audit_msg, 512, "RequestUserId error");
		goto loser;
	}
    
    PR_snprintf((char *)configname, 256, "%s.%s.auth.enable", OP_PREFIX, tokenType);

	if (!AuthenticateUser(session, configname, cuid, extensions, 
				tokenType, login, userid, status)){
                PR_snprintf(audit_msg, 512, "AuthenticateUser error");
		goto loser;
	}

    RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
        userid != NULL ? userid : "",
        cuid != NULL ? cuid : "",
        msn != NULL ? msn : "",
        "success",
        "enrollment",
        final_applet_version != NULL ? final_applet_version : "",
        keyVersion != NULL ? keyVersion : "",
        "token login successful");

        // get authid for audit log
        PR_snprintf((char *)configname, 256, "%s.%s.auth.id", OP_PREFIX, tokenType);
        authid = RA::GetConfigStore()->GetConfigAsString(configname);

	StatusUpdate(session, extensions, 4, "PROGRESS_APPLET_UPGRADE");

        if(do_force_format)  {
            bool skip_auth = true;
            if(Format(session,extensions,skip_auth) != STATUS_NO_ERROR )  {
                    PR_snprintf(audit_msg,512, "ForceUpgradeApplet error");
                    status = STATUS_ERROR_MAC_ENROLL_PDU; 
                    goto loser;
                } else {
                    RA::Debug(LL_PER_CONNECTION, "RA_Enroll_Processor::Process",
                              "after Successful ForceUpdgradeApplet, succeeded!");

                    PR_snprintf(audit_msg,512, "ForceUpgradeApplet succeeded as per policy.");
                   status = STATUS_NO_ERROR;
                    goto loser;

                }
        }  else {
            if (! CheckAndUpgradeApplet(
		    session,
		    extensions,
		    cuid,
		    tokenType,
		    final_applet_version,
		    app_major_version, app_minor_version,
		    //appletVersion,
		    NetKeyAID,
               	    msn,
            	    userid,
		    status, 
       		    &keyVersion)) {
                PR_snprintf(audit_msg, 512, "CheckAndUpgradeApplet error");
		goto loser;
	      }
      }

      RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
        userid != NULL ? userid : "",
        cuid != NULL ? cuid : "",
        msn != NULL ? msn : "",
        "success",
        "enrollment",
        final_applet_version != NULL ? final_applet_version : "",
        keyVersion != NULL ? keyVersion : "",
        "applet upgraded successfully");

    isPinPresent = IsPinPresent(session, 0x0);

	StatusUpdate(session, extensions, 12, "PROGRESS_KEY_UPGRADE");

	if (!CheckAndUpgradeSymKeys(
		session,
		extensions,
		cuid,
		tokenType,
		msn,
                final_applet_version,
                userid,
                keyVersion,
		CardManagerAID,
		NetKeyAID,
		channel,
		status)) 
	{
                PR_snprintf(audit_msg, 512, "CheckAndUpgradeSymKeys error");
		goto loser;
	}
		
    /* we should have a good channel here */
    if (channel == NULL) {
            RA::Error(FN, "no good channel");
            status = STATUS_ERROR_CREATE_CARDMGR;
            PR_snprintf(audit_msg, 512, "secure channel setup error");
            goto loser;
    }

    if (channel != NULL) {
	if( keyVersion != NULL ) {
		PR_Free( (char *) keyVersion );
		keyVersion = NULL;
	}
        keyVersion = Util::Buffer2String(channel->GetKeyInfoData());
    }
    
	StatusUpdate(session, extensions, 14, "PROGRESS_TOKEN_AUTHENTICATION");

    rc = channel->ExternalAuthenticate();
    if (rc == -1) {
      RA::Error(FN, "external authenticate failed");
        status = STATUS_ERROR_CREATE_CARDMGR;
        PR_snprintf(audit_msg, 512, "external authentication error");
        goto loser;
    }

    RA::Debug(LL_PER_CONNECTION, FN, "after SetupSecureChannel, succeeded");

    PR_snprintf((char *)configname, 256, "%s.%s.pinReset.enable", OP_PREFIX, tokenType);
    if (RA::GetConfigStore()->GetConfigAsBool(configname, 1)) {

      PR_snprintf((char *)configname, 256, "%s.%s.pinReset.pin.minLen", OP_PREFIX, tokenType);
      unsigned int minlen = RA::GetConfigStore()->GetConfigAsUnsignedInt(configname, 4);
      PR_snprintf((char *)configname, 256,"%s.%s.pinReset.pin.maxLen", OP_PREFIX, tokenType);
      unsigned int maxlen = RA::GetConfigStore()->GetConfigAsUnsignedInt(configname, 10);
     
      new_pin = RequestNewPin(session, minlen, maxlen);
      if (new_pin == NULL) {
	RA::Error(FN, "new pin request failed");

        status = STATUS_ERROR_MAC_RESET_PIN_PDU;
        PR_snprintf(audit_msg, 512, "new pin request error");
        goto loser;
      }
      RA::Debug(LL_PER_CONNECTION, "RA_Enroll_Processor::Process",
	      "after RequestNewPin, succeeded");

    RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
        userid != NULL ? userid : "",
        cuid != NULL ? cuid : "",
        msn != NULL ? msn : "",
        "success",
        "enrollment",
        final_applet_version != NULL ? final_applet_version : "",
        keyVersion != NULL ? keyVersion : "",
        "RequestNewPin completed successfully");

    PR_snprintf((char *)configname, 256, "%s.%s.pinReset.enable", OP_PREFIX, tokenType);
    if (RA::GetConfigStore()->GetConfigAsBool(configname, 1)) {
      if (!isPinPresent) {
    	PR_snprintf((char *)configname, 256, "%s.%s.pinReset.pin.maxRetries", OP_PREFIX, tokenType);
	maxRetries = RA::GetConfigStore()->GetConfigAsInt(configname, 0x7f);
        RA::Debug(LL_PER_CONNECTION, FN,
	      "param=%s maxRetries=%d", configname, maxRetries);
        rc = channel->CreatePin(0x0, 
		maxRetries,
		RA::GetConfigStore()->GetConfigAsString("create_pin.string", "password"));
        if (rc == -1) {
	    RA::Error("RA_Enroll_Processor::Process",
		  "create pin failed");

            status = STATUS_ERROR_MAC_RESET_PIN_PDU;
            PR_snprintf(audit_msg, 512, "create pin request error");
            goto loser;
        }


        RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
           userid != NULL ? userid : "",
           cuid != NULL ? cuid : "",
           msn != NULL ? msn : "",
           "success",
           "enrollment",
           final_applet_version != NULL ? final_applet_version : "",
           keyVersion != NULL ? keyVersion : "",
           "CreatePin completed successfully");

      }
    }

      rc = channel->ResetPin(0x0, new_pin);
      if (rc == -1) {
	  RA::Error("RA_Enroll_Processor::Process",
		  "reset pin failed");

          status = STATUS_ERROR_MAC_RESET_PIN_PDU;
          PR_snprintf(audit_msg, 512, "reset pin request error");
          goto loser;
      }

      RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
        userid != NULL ? userid : "",
        cuid != NULL ? cuid : "",
        msn != NULL ? msn : "",
        "success",
        "enrollment",
        final_applet_version != NULL ? final_applet_version : "",
        keyVersion != NULL ? keyVersion : "",
        "ResetPin completed successfully");
    }

    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
	      "after ResetPin, succeeded");

    // to help testing, we may use fix challenge
    PR_snprintf((char *)configname, 256, "%s.%s.generateChallenge", OP_PREFIX, tokenType);
    if (RA::GetConfigStore()->GetConfigAsBool(configname, 1)) {
      /* generate challenge for enrollment */
      RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
	      "Generate Challenge");
/*
 random number generation moved to TKS
      rc = Util::GetRandomChallenge(*plaintext_challenge);
      if (rc == -1) {
	RA::Error("RA_Enroll_Processor::Process",
		  "random challenge creation failed");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        RA::tdb_activity(session->GetRemoteIP(), cuid, "enrollment", "failure", "general challenge error", "", tokenType);
        goto loser;
      }
*/

    }
    kdd =  channel->GetKeyDiversificationData();
    khex = kdd.toHex();
    RA::Debug("RA_Enroll_Processor::Process", "cuid=%s", khex);

    PR_snprintf((char *)configname, 256, "%s.%s.tks.conn", OP_PREFIX, tokenType);
    connid = RA::GetConfigStore()->GetConfigAsString(configname);
    /* wrap challenge with KEK key */
    rc = EncryptData(kdd,
      channel->GetKeyInfoData(), *plaintext_challenge, *wrapped_challenge, connid);
    if (rc == -1) {
	RA::Error("RA_Enroll_Processor::Process",
		  "encryt data failed");
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        PR_snprintf(audit_msg, 512, "challenge encryption error");
        goto loser;
    }
    // read objects back
    PR_snprintf((char *)configname, 256, "%s.%s.pkcs11obj.enable", 
		    OP_PREFIX, tokenType);
    pkcs11obj_enable = RA::GetConfigStore()->GetConfigAsBool(configname, 1);

    if (pkcs11obj_enable) {
      pkcs11objx = new PKCS11Obj();

      // read old objects
      seq = 0x00;
      lastFormatVersion = 0x0100;
      //      lastObjectVersion = 0;
      if (getRandomNumber(&lastObjectVersion) != SECSuccess) {
          RA::Error(LL_PER_PDU, "RA_Enroll_Processor::Process",
	    "Could not generate a random version number...assigning 0x00");
          lastObjectVersion = 0x00;
      } else {
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
            "got random version numer: %ul", lastObjectVersion);
      }

      foundLastObjectVersion = 0;
      do {
        object = ListObjects(session, seq);
	if (object == NULL) {
		seq = 0;
	} else {
		seq = 1; // get next entry
		Buffer objectID = object->substr(0, 4);
		Buffer objectLen = object->substr(4, 4);
		unsigned long objectIDVal = 
			((((BYTE *)objectID)[0] << 24)) + 
			((((BYTE *)objectID)[1] << 16)) + 
			((((BYTE *)objectID)[2] << 8)) + 
			((((BYTE *)objectID)[3]));
		unsigned long objectLenVal = 
			((((BYTE *)objectLen)[0] << 24)) + 
			((((BYTE *)objectLen)[1] << 16)) + 
			((((BYTE *)objectLen)[2] << 8)) + 
			((((BYTE *)objectLen)[3]));

		Buffer *o = channel->ReadObject((BYTE*)objectID, 0, 
				(int)objectLenVal);
        if (o == NULL) {
          status = STATUS_ERROR_CREATE_TUS_TOKEN_ENTRY;
          PR_snprintf(audit_msg, 512, "error in creating token entry");
          goto loser;
        }
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
                     "object read from token");

		if (((unsigned char *)objectID)[0] == 'z' && 
				((unsigned char *)objectID)[1] == '0') {
			lastFormatVersion = (((BYTE*)*o)[0] << 8) + 
					(((BYTE*)*o)[1]);
			lastObjectVersion = (((BYTE*)*o)[2] << 8) + 
					(((BYTE*)*o)[3]);
      			foundLastObjectVersion = 1;

			//
			delete pkcs11objx;
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
                     "parsing pkcs11obj read from token");
			pkcs11objx = PKCS11Obj::Parse(o, 0);
			seq = 0;
		} else {
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
                     "new pkcs11obj");
			ObjectSpec *objSpec = 
				ObjectSpec::ParseFromTokenData(objectIDVal, o);
			if (objSpec != NULL) {
				pkcs11objx->AddObjectSpec(objSpec);
			}
		}

		delete o; 
		delete object;
	}
      } while (seq != 0);

    }

    rc = RA::tdb_add_token_entry((char *)userid, cuid, "uninitialized", tokenType);
    if (rc == -1) {
        status = STATUS_ERROR_CREATE_TUS_TOKEN_ENTRY;
        PR_snprintf(audit_msg, 512, "error in creating uninitialized token entry");
        goto loser;
    }

	StatusUpdate(session, extensions, 15, "PROGRESS_PROCESS_PROFILE");

    tokentype = (char *)malloc(256 * sizeof(char)) ;
    PL_strcpy(tokentype, tokenType);
    /* generate signing key on netkey */
    if (!GenerateCertsAfterRecoveryPolicy(login, session, origins, ktypes, tokentype, pkcs11objx, 
      pkcs11obj_enable, extensions, channel, wrapped_challenge, 
      key_check, plaintext_challenge, cuid, msn, final_applet_version, 
      khex, userid, status, certificates, o_certNums, tokenTypes)) {
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process"," - GenerateCertsAfterRecoveryPolicy returns false");
        goto loser;
    } else {
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process"," - GenerateCertsAfterRecoveryPolicy returns true");
        if (status == STATUS_NO_ERROR) {
            RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process"," - after GenerateCertsAfterRecoveryPolicy", "status is STATUS_NO_ERROR");
            if (!GenerateCertificates(login, session, origins, ktypes, tokentype, pkcs11objx, 
              pkcs11obj_enable, extensions, channel, wrapped_challenge, 
              key_check, plaintext_challenge, cuid, msn, final_applet_version, 
              khex, userid, status, certificates, o_certNums, tokenTypes)) {
                RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process - after GenerateCertificates"," returns false might as well clean up token.");
                bool skip_auth = true;
                Format(session,extensions,skip_auth);
                goto loser;
            } else {
                RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process - after GenerateCertificates"," returns true");
            }
        } else {
            RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process - after GenerateCertsAfterRecoveryPolicy", "status is %d", status);
        }
    }

    if ((status == STATUS_ERROR_RENEWAL_IS_PROCESSED) &&
            RA::ra_allow_token_renew(cuid)) {
        renewed = true;
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "renewal happened.. "); 
    }
    
    // read objects back
    if (pkcs11obj_enable) {
      RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "pkcs11obj enabled"); 
      pkcs11objx->SetFormatVersion(lastFormatVersion);
      if (foundLastObjectVersion) {
          while (lastObjectVersion == 0xff) {
              if (getRandomNumber(&lastObjectVersion) != SECSuccess) {
                  RA::Error(LL_PER_PDU, "RA_Enroll_Processor::Process",
                    "Encounter 0xff, could not generate a random version number...assigning 0x00");
                  lastObjectVersion = 0x00;
              } else {
                  RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
                    "Encounter 0xff, got random version numer: %ul", lastObjectVersion);
              }
           }

           pkcs11objx->SetObjectVersion(lastObjectVersion+1);
      } else {
      	pkcs11objx->SetObjectVersion(lastObjectVersion);
      }
      pkcs11objx->SetCUID(token_cuid);

      /* add additional certificate objects */
      PR_snprintf((char *)configname, 256, "%s.certificates.num", 
		    OP_PREFIX);
      int certNum = RA::GetConfigStore()->GetConfigAsInt(configname);
      if (certNum > 0) {
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "about to write certificate chain");
      }
      for (int i = 0; i < certNum; i++) {

        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "root certificate #%d", i);

        PR_snprintf((char *)configname, 256, "%s.certificates.value.%d", 
		    OP_PREFIX, i);
        char *certName = (char *)RA::GetConfigStore()->GetConfigAsString(configname);

        /* retrieve certificate info */
        PR_snprintf((char *)configname, 256, "%s.certificates.%s.nickName", 
		    OP_PREFIX, certName);
        char *certNickName = (char *)RA::GetConfigStore()->GetConfigAsString(configname);
        PR_snprintf((char *)configname, 256, "%s.certificates.%s.certId", 
		    OP_PREFIX, certName);
        char *certId = (char *)
          RA::GetConfigStore()->GetConfigAsString(configname, "C0");

/*
op.enroll.certificates.num=1
op.enroll.certificates.value.0=caCert
op.enroll.certificates.caCert.nickName=caCert0 fpki-tps
op.enroll.certificates.caCert.certId=C5
op.enroll.certificates.caCert.certAttrId=c5
op.enroll.certificates.caCert.label=caCert Label
 */

        /* retrieve certificate */
        CERTCertificate *cert = CERT_FindCertByNickname(
                CERT_GetDefaultCertDB(), certNickName);

        if (cert == NULL) {
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Cannot find certificate %s", certNickName);
        } else {
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Found certificate %s", certNickName);

          /* add certificate to z object */
          Buffer *certBuf = new Buffer((BYTE*)cert->derCert.data, 
                        (unsigned int)cert->derCert.len);
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Certificate buffer created");
	      ObjectSpec *objSpec = ObjectSpec::ParseFromTokenData(
				(certId[0] << 24) +
				(certId[1] << 16), certBuf);
	      pkcs11objx->AddObjectSpec(objSpec);
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Certificate object Added to PKCS11 Object");

          /* add PK11 attributes */
        PR_snprintf((char *)configname, 256, "%s.certificates.%s.label", 
		    OP_PREFIX, certName);
        char *certLabel = (char *)RA::GetConfigStore()->GetConfigAsString(configname);
        PR_snprintf((char *)configname, 256, "%s.certificates.%s.certAttrId", 
		    OP_PREFIX, certName);
        char *certAttrId = (char *)
          RA::GetConfigStore()->GetConfigAsString(configname, "c0");

          Buffer *keyid = NULL;
          if (cert->subjectKeyID.data != NULL) {
            keyid = new Buffer((BYTE*)cert->subjectKeyID.data,
                                    (unsigned int)cert->subjectKeyID.len);
          } else {
            SECItem *pubKeyData = PK11_GetPubIndexKeyID(cert) ;
            SECItem *tmpitem = PK11_MakeIDFromPubKey(pubKeyData);
            RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Got Key ID");
         
             
            keyid = new Buffer((BYTE*)tmpitem->data, 
                                         (unsigned int)tmpitem->len);
          }

          Buffer b = channel->CreatePKCS11CertAttrsBuffer(
                   KEY_TYPE_ENCRYPTION /* not being used */, 
                   certAttrId, certLabel, keyid);
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Created buffer for PKCS11 cert attributes");
	      objSpec = ObjectSpec::ParseFromTokenData(
							   (certAttrId[0] << 24) +
							   (certAttrId[1] << 16),
							   &b);
	      pkcs11objx->AddObjectSpec(objSpec);
          RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", 
              "Added PKCS11 certificate attribute");
        }
      }
      
      // build label
      PR_snprintf((char *)configname, 256, "%s.%s.keyGen.tokenName", 
		    OP_PREFIX, tokentype);
      RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "tokenName '%s'",
		   configname);
      pattern = RA::GetConfigStore()->GetConfigAsString(configname, "$cuid$");
      nv.Add("cuid", cuid);
      nv.Add("msn", msn);
      nv.Add("userid", userid);
      nv.Add("profileId", tokenType);

      /* populate auth parameters output to nv also */
      /* so we can reference to the auth parameter by */
      /* using $auth.cn$, or $auth.mail$ */
      RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "Check login");
      if (login != NULL) {
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "Found login");
        int s = login->Size();
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "login size=%d", s);
        for (int x = 0; x < s; x++) {
           char namebuf[2048];
           char *name = login->GetNameAt(x);
           sprintf(namebuf, "auth.%s", name);
           if (strcmp(name,"PASSWORD") != 0) {
             RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "Exposed %s=%s", namebuf, login->GetValue(name));
           }
           nv.Add(namebuf, login->GetValue(name));
        }
      }
      label = MapPattern(&nv, (char *) pattern);
      RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "labelName '%s'",
		   label);
      labelBuffer = Buffer((BYTE*)label, strlen(label));
      pkcs11objx->SetTokenName(labelBuffer); 

      // write PKCS11 Obj
      BYTE objid[4];

      objid[0] = 'z';
      objid[1] = '0';
      objid[2] = 0;
      objid[3] = 0;
      Buffer xb;

      PR_snprintf((char *)configname, 256, "%s.%s.pkcs11obj.compress.enable", 
		    OP_PREFIX, tokentype);
      compress = RA::GetConfigStore()->GetConfigAsBool(configname, 1);

      if (compress) {
      	xb = pkcs11objx->GetCompressedData(); 
        RA::Debug("RA_Enroll_Processor::Process PKCSData", "Compressed Data");
      } else {
      	xb = pkcs11objx->GetData(); 
        RA::Debug("RA_Enroll_Processor::Process PKCSData", "Uncompressed Data");
      }
      RA::DebugBuffer("RA_Enroll_Processor::Process PKCSData", "PKCS Data=", &xb);


      if(xb.size() == 0)  {
          status = STATUS_ERROR_MAC_ENROLL_PDU;
          RA::Debug("RA_Enroll_Processor::Failure to get token object!"," failed");
          PR_snprintf(audit_msg, 512, "channel createObject failed");
          goto loser;
      }

      if((int) xb.size() > totalAvailableMemory) {
          status = STATUS_ERROR_MAC_ENROLL_PDU;
          RA::Debug("RA_Enroll_Processor::Failure pkcs11 object may exceed applet memory"," failed");
          PR_snprintf(audit_msg, 512, "Applet memory exceeded when writing out final token data");
          bool skip_auth = true;
          if(!renewed) { //Renewal should leave what they have on the token.
          	Format(session,extensions,skip_auth);
          }
          goto loser;
      }

	BYTE perms[6];

	perms[0] = 0xff;
	perms[1] = 0xff;
	perms[2] = 0x40;
	perms[3] = 0x00;
	perms[4] = 0x40;
	perms[5] = 0x00;

	if (channel->CreateObject(objid, perms, xb.size()) != 1) {
	  status = STATUS_ERROR_MAC_ENROLL_PDU;
          RA::Debug("RA_Enroll_Processor::channel createObject"," failed");
          PR_snprintf(audit_msg, 512, "channel createObject failed");
	  goto loser;
	}
      //      channel->CreateObject(objid, xb.size());
	if (channel->WriteObject(objid, (BYTE*)xb, xb.size()) != 1) {
	  status = STATUS_ERROR_MAC_ENROLL_PDU;
          RA::Debug("RA_Enroll_Processor::channel writeObject"," failed");
          PR_snprintf(audit_msg, 512, "channel writeObject failed");
	  goto loser;
	}
    }

	StatusUpdate(session, extensions, 90, "PROGRESS_SET_LIFE_CYCLE_STATE");
    
    // add issuer info to the token
    PR_snprintf((char *)configname, 256, "%s.%s.issuerinfo.enable",
          OP_PREFIX, tokenType);
    RA::Debug("RA_Enroll_Processor", "Getting %s", configname);
    if (RA::GetConfigStore()->GetConfigAsBool(configname, 0)) {
        if (channel != NULL) {
            char issuer[224];
            for (int i = 0; i < 224; i++) {
              issuer[i] = 0;
            }
            PR_snprintf((char *)configname, 256, "%s.%s.issuerinfo.value",
               OP_PREFIX, tokenType);
            char *issuer_val = (char*)RA::GetConfigStore()->GetConfigAsString(
                                   configname);
            RA::Debug("RA_Enroll_Processor", 
              "Before pattern substitution mapping is %s", issuer_val);
            issuer_val = MapPattern(&nv, (char *) issuer_val);
            RA::Debug("RA_Enroll_Processor", 
              "After pattern substitution mapping is %s", issuer_val);
            sprintf(issuer, "%s", issuer_val);
            RA::Debug("RA_Enroll_Processor", "Set Issuer Info %s", issuer_val);
            Buffer *info = new Buffer((BYTE*)issuer, 224);
            rc = channel->SetIssuerInfo(info);
      
            if (info != NULL) {
                delete info;
                info = NULL;
            }
        }
    }
    /* write lifecycle bit */
    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "Set Lifecycle State");
    rc = channel->SetLifecycleState(0x0f);
    if (rc == -1) {
        RA::Error("RA_Enroll_Processor::Process",
		"Set life cycle state failed");
        status = STATUS_ERROR_MAC_LIFESTYLE_PDU;
        PR_snprintf(audit_msg, 512, "set life cycle state error");
        goto loser;
    }

    rc = channel->Close();
    if (rc == -1) {
        RA::Error("RA_Enroll_Processor::Process",
		"Failed to close channel");
        status = STATUS_ERROR_CONNECTION;
        PR_snprintf(audit_msg, 512, "channel not closed");
        goto loser;
    }
    
	StatusUpdate(session, extensions, 100, "PROGRESS_DONE");

    status = STATUS_NO_ERROR;

    sprintf(activity_msg, "applet_version=%s tokenType=%s userid=%s", 
           final_applet_version, tokentype, userid);

    if (renewed) {
        RA::tdb_activity(session->GetRemoteIP(), cuid, "renewal", "success", activity_msg, userid, tokenType);
    } else {
        RA::tdb_activity(session->GetRemoteIP(), cuid, "enrollment", "success", activity_msg, userid, tokenType);
    }
    RA::tdb_update((char *)userid, cuid, (char *)final_applet_version, (char *)keyVersion, "active", "", tokenType);
    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "after tdb_update()");

    RA::tdb_update_certificates(cuid, tokenTypes, (char*)userid, certificates, ktypes, origins, o_certNums);
    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "after tdb_update_certificates()");

    rc = 1;

    end = PR_IntervalNow();
    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "after end");

    /* audit log for successful enrollment */
    if (renewed) { 
        if (authid != NULL) { 
            PR_snprintf(activity_msg, 4096, "renewal processing completed, authid = %s", authid);
        } else {
            PR_snprintf(activity_msg, 4096, "renewal processing completed");
        }
        RA::Audit(EV_RENEWAL, AUDIT_MSG_PROC,
          userid, cuid, msn, "success", "renewal", final_applet_version, keyVersion, activity_msg);
    } else { 
        if (authid != NULL) { 
            PR_snprintf(activity_msg, 4096, "enrollment processing completed, authid = %s", authid);
        } else {
            PR_snprintf(activity_msg, 4096, "enrollment processing completed");
        }
        RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
          userid, cuid, msn, "success", "enrollment", final_applet_version, keyVersion, activity_msg);
    }

    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "after audit, o_certNums=%d",o_certNums);

loser:

    if (strlen(audit_msg) > 0) { // a failure occurred
        if (renewed) { 
            RA::Audit(EV_RENEWAL, AUDIT_MSG_PROC,
              userid != NULL ? userid : "", 
              cuid != NULL ? cuid : "", 
              msn != NULL ? msn : "", 
              "failure", 
              "renewal", 
              final_applet_version != NULL ? final_applet_version : "", 
              keyVersion != NULL ? keyVersion : "", 
              audit_msg);

            if ((cuid != NULL) && (tokenType != NULL)) {
                RA::tdb_activity(session->GetRemoteIP(),
                    cuid, 
                    "renewal", 
                    "failure",
                    audit_msg, 
                    userid != NULL? userid : "", 
                    tokenType);
            }
        } else { 
            RA::Audit(EV_ENROLLMENT, AUDIT_MSG_PROC,
              userid != NULL ? userid : "", 
              cuid != NULL ? cuid : "", 
              msn != NULL ? msn : "", 
              "failure", 
              "enrollment", 
              final_applet_version != NULL ? final_applet_version : "", 
              keyVersion != NULL ? keyVersion : "", 
              audit_msg);

            if ((cuid != NULL) && (tokenType != NULL)) {
                RA::tdb_activity(session->GetRemoteIP(),
                    cuid, 
                    "enrollment", 
                    "failure",
                    audit_msg, 
                    userid != NULL? userid : "", 
                    tokenType);
            }
        }
    }

    if (tokenTypes != NULL) {
        for (int nn=0; nn<o_certNums; nn++) {
            if (tokenTypes[nn] != NULL)
                PL_strfree(tokenTypes[nn]);
            tokenTypes[nn] = NULL;
        }
        free(tokenTypes);
        tokenTypes = NULL;
    }
    if (certificates != NULL) {
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "before CERT_DestroyCertificate.  certNums=%d", o_certNums);
        for (int i=0;i < o_certNums; i++) {
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "CERT_DestroyCertificate:  i=%d", i);
            if (certificates[i] != NULL) {
                   CERT_DestroyCertificate(certificates[i]);
            }
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "CERT_DestroyCertificate:  i=%i done", i);
        }
        free(certificates);
        RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "after CERT_DestroyCertificate");
    }

    if( certEnroll != NULL ) {
        delete certEnroll;
        certEnroll = NULL;
    }

    if (ktypes != NULL) {
       for (int nn=0; nn < o_certNums; nn++) {
           if (ktypes[nn] != NULL)
               PL_strfree(ktypes[nn]);
           ktypes[nn] = NULL;
       } 
       free(ktypes);
       ktypes = NULL;
    }

    if (origins != NULL) {
       for (int nn=0; nn < o_certNums; nn++) {
           if (origins[nn] != NULL)
               PL_strfree(origins[nn]);
           origins[nn] = NULL;
       }
       free(origins);
       origins = NULL;
    }

    if( CardManagerAID != NULL ) {
        delete CardManagerAID;
        CardManagerAID = NULL;
    }

    if( NetKeyAID != NULL ) {
        delete NetKeyAID;
        NetKeyAID = NULL;
    }

    if( login != NULL ) {
        delete login;
        login = NULL;
    }

    if( channel != NULL ) {
        delete channel;
        channel = NULL;
    }

    if( new_pin != NULL ) {
        PL_strfree( new_pin );
        new_pin = NULL;
    }

    if( key_check != NULL ) {
        delete key_check;
        key_check = NULL;
    }

    if( wrapped_challenge != NULL ) {
        delete wrapped_challenge;
        wrapped_challenge = NULL;
    }

    if( plaintext_challenge != NULL ) {
        delete plaintext_challenge;
        plaintext_challenge = NULL;
    }

    if( token_status != NULL ) {
        delete token_status;
        token_status = NULL;
    }
    
    if( final_applet_version != NULL ) {
        PR_Free( (char *) final_applet_version );
        final_applet_version = NULL;
    }
 
    if( appletVersion != NULL ) {
        PR_Free( (char *) appletVersion );
        appletVersion = NULL;
    }
    if( khex != NULL ) {
        PR_Free( khex );
        khex = NULL;
    }
    if( keyVersion != NULL ) {
        PR_Free( (char *) keyVersion );
        keyVersion = NULL;
    }
    if( userid != NULL ) {
        PR_Free( (char *) userid );
        userid = NULL;
    }
    if (token_state != NULL) {
        PR_Free((char *)token_state);
        token_state = NULL;
    }
    if( cuid != NULL ) {
        PR_Free( cuid );
        cuid = NULL;
    }
    if( msn != NULL ) {
        PR_Free( msn );
        msn = NULL;
    }
    if( label != NULL ) {
        PL_strfree( (char *) label );
        label = NULL;
    }
    if (tokentype != NULL) {
      PR_Free(tokentype);
    }
    if (pkcs11objx != NULL) {
      delete pkcs11objx;
    }

#ifdef   MEM_PROFILING     
            MEM_dump_unfree();
#endif

    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process", "returning status");
    return status;
}


bool RA_Enroll_Processor::GenerateCertificates(AuthParams *login, RA_Session *session, char **&origins, char **&ktypes, 
  char *tokenType, PKCS11Obj *pkcs11objx, int pkcs11obj_enable, 
  NameValueSet *extensions, Secure_Channel *channel, Buffer *wrapped_challenge,
  Buffer *key_check, Buffer *plaintext_challenge, char *cuid, char *msn,
  const char *final_applet_version, char *khex, const char *userid, RA_Status &o_status, 
  CERTCertificate **&certificates, int &o_certNums, char **&tokenTypes) {

    bool noFailedCerts = true;
    bool r=true;
    int keyTypeNum = 0;
    int i = 0;
    char configname[256];
	const char *FN = "RA_Enroll_Processor::GenerateCertificates";
    RA_Status lastErrorStatus = STATUS_NO_ERROR;


    RA::Debug(LL_PER_CONNECTION,FN, "tokenType=%s", tokenType); 
    PR_snprintf((char *)configname, 256, "%s.%s.keyGen.keyType.num", OP_PREFIX, tokenType);
    keyTypeNum = RA::GetConfigStore()->GetConfigAsInt(configname);
    if (keyTypeNum == 0) {
        r = false;
        RA::Error(LL_PER_CONNECTION,FN,
                        "Profile parameters are not found");
        o_status = STATUS_ERROR_DEFAULT_TOKENTYPE_PARAMS_NOT_FOUND;
        goto loser; 
    }

    ktypes = (char **) malloc (sizeof(char *) * keyTypeNum);
    origins = (char **) malloc (sizeof(char *) * keyTypeNum);
    tokenTypes = (char **) malloc (sizeof(char *) * keyTypeNum);
    
    certificates = (CERTCertificate **) malloc (sizeof(CERTCertificate *) * keyTypeNum);
    o_certNums = keyTypeNum;
    for (i=0; i<keyTypeNum; i++) {
		certificates[i] = NULL;
		ktypes[i] = NULL;
		origins[i] = NULL;
		tokenTypes[i] = NULL;

    }
    for (i=0; i<keyTypeNum; i++) {

        PR_snprintf((char *)configname, 256, "%s.%s.keyGen.keyType.value.%d", OP_PREFIX, tokenType, i);
        const char *keyTypeValue = RA::GetConfigStore()->GetConfigAsString(configname, "signing");

        r = GenerateCertificate(login,keyTypeNum, keyTypeValue, i, session, origins, ktypes, tokenType,
          pkcs11objx, pkcs11obj_enable, extensions, channel, wrapped_challenge,
          key_check, plaintext_challenge, cuid, msn, final_applet_version,
          khex, userid, o_status, certificates);

        RA::Debug("GenerateCertificates","configname %s  result  %d",configname,r);

        tokenTypes[i] = PL_strdup(tokenType);
        if(r == false)  {
            noFailedCerts  = false;
            lastErrorStatus = o_status;
            break;
       }
            
    }

    if (noFailedCerts == true) {
    //In this special case of re-enroll
    //Revoke  current certs for this token  
    // before the just enrolled certs are written to the db
         char error_msg[512];
         bool success = RevokeCertificates(session, cuid,error_msg,(char *)final_applet_version,
                                             NULL,(char *)tokenType,(char *)userid,o_status
         );

         RA::Debug("GenerateCertificates","Revoke result %d  ",(int) success);

         if (!success) {
              //Don't blow the whole thing up for this.
              RA::Debug("GenerateCertificates","Revocation failure %s  ",error_msg);
         }

    }
 loser:
    if(lastErrorStatus != STATUS_NO_ERROR) {
        o_status = lastErrorStatus;
    }
    return noFailedCerts;
}

bool RA_Enroll_Processor::GenerateCertificate(AuthParams *login, int keyTypeNum, const char *keyTypeValue, int i, RA_Session *session, 
  char **origins, char **ktypes, char *tokenType, PKCS11Obj *pkcs11objx, int pkcs11obj_enable,
  NameValueSet *extensions, Secure_Channel *channel, Buffer *wrapped_challenge,
  Buffer *key_check, Buffer *plaintext_challenge, char *cuid, char *msn,
  const char *final_applet_version, char *khex, const char *userid, 
  RA_Status &o_status, CERTCertificate **certificates)
{
    bool r = true;
    char configname[256];
    char keyTypePrefix[200];
	const char *FN="RA_Enroll_Processor::GenerateCertificate";

    PR_snprintf((char *)keyTypePrefix, 256, "%s.%s.keyGen.%s", OP_PREFIX, tokenType, keyTypeValue);
    RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::GenerateCertificate","keyTypePrefix is %s",keyTypePrefix);
    PR_snprintf((char *)configname, 256, "%s.ca.profileId", keyTypePrefix);
    const char *profileId = RA::GetConfigStore()->GetConfigAsString(configname, "");
    PR_snprintf((char *)configname, 256,"%s.certId", keyTypePrefix);
    const char *certId = RA::GetConfigStore()->GetConfigAsString(configname, "C0");
    PR_snprintf((char *)configname, 256, "%s.certAttrId", keyTypePrefix);
    const char *certAttrId = RA::GetConfigStore()->GetConfigAsString(configname, "c0");
    PR_snprintf((char *)configname, 256, "%s.privateKeyAttrId", keyTypePrefix);
    const char *priKeyAttrId = RA::GetConfigStore()->GetConfigAsString(configname, "k0"); 
    PR_snprintf((char *)configname,  256,"%s.publicKeyAttrId", keyTypePrefix);
    const char *pubKeyAttrId = RA::GetConfigStore()->GetConfigAsString(configname, "k1");
    PR_snprintf((char *)configname, 256, "%s.keySize", keyTypePrefix);
    int keySize = RA::GetConfigStore()->GetConfigAsInt(configname, 1024);


    PR_snprintf((char *)configname, 256, "%s.alg", keyTypePrefix);
    //Default RSA_CRT=2
    BYTE algorithm = (BYTE) RA::GetConfigStore()->GetConfigAsInt(configname, 2);

    PR_snprintf((char *)configname, 256, "%s.publisherId", keyTypePrefix);
    const char *publisherId = RA::GetConfigStore()->GetConfigAsString(configname, NULL);

    PR_snprintf((char *)configname, 256, "%s.keyUsage", keyTypePrefix);
    int keyUsage = RA::GetConfigStore()->GetConfigAsInt(configname, 0);
    PR_snprintf((char *)configname, 256, "%s.keyUser", keyTypePrefix);
    int keyUser = RA::GetConfigStore()->GetConfigAsInt(configname, 0);
    PR_snprintf((char *)configname, 256, "%s.privateKeyNumber", keyTypePrefix);
    int priKeyNumber = RA::GetConfigStore()->GetConfigAsInt(configname, 0);
    PR_snprintf((char *)configname, 256, "%s.publicKeyNumber", keyTypePrefix);
    int pubKeyNumber = RA::GetConfigStore()->GetConfigAsInt(configname, 1);


    // get key capabilites to determine if the key type is SIGNING, 
    // ENCRYPTION, or SIGNING_AND_ENCRYPTION
    PR_snprintf((char *)configname, 256, "%s.private.keyCapabilities.sign", keyTypePrefix);
    bool isSigning = RA::GetConfigStore()->GetConfigAsBool(configname);
    PR_snprintf((char *)configname, 256, "%s.public.keyCapabilities.encrypt", keyTypePrefix);
    bool isEncrypt = RA::GetConfigStore()->GetConfigAsBool(configname);
    int keyTypeEnum = 0;

    if ((isSigning) &&
        (isEncrypt)) {
        keyTypeEnum = KEY_TYPE_SIGNING_AND_ENCRYPTION;
    } else if (isSigning) {
        keyTypeEnum = KEY_TYPE_SIGNING;
    } else if (isEncrypt) {
        keyTypeEnum = KEY_TYPE_ENCRYPTION;
    }
    RA::Debug(LL_PER_CONNECTION,FN,
		"key type is %d",keyTypeEnum);

    PR_snprintf((char *)configname, 256, "%s.ca.conn", keyTypePrefix);
    const char *caconnid = RA::GetConfigStore()->GetConfigAsString(configname);
    certificates[i] = NULL;
    ktypes[i] = NULL;
    origins[i] = NULL;

    o_status = DoEnrollment(login, session, certificates, origins, ktypes, pkcs11obj_enable,
                    pkcs11objx, extensions, i, keyTypeNum,
                    15 /* start progress */,
                    90 /* end progress */, channel, wrapped_challenge,
          tokenType,
          keyTypeValue,
          key_check,
          plaintext_challenge,
          cuid,
          msn,
          khex, (TokenKeyType)keyTypeEnum, profileId, userid, certId,publisherId, certAttrId, priKeyAttrId,
          pubKeyAttrId, (keyUser << 4)+priKeyNumber,
          (keyUsage << 4)+pubKeyNumber, algorithm, keySize, caconnid, keyTypePrefix,(char *)final_applet_version);

    if (o_status != STATUS_NO_ERROR) {
        r = false;

        RA::Debug(LL_PER_CONNECTION,FN,
			"Got a status error from DoEnrollment:  %d", o_status);
        RA::tdb_activity(session->GetRemoteIP(), cuid, "enrollment", "failure", "enrollment error", "", tokenType);
        goto loser;
    }

 loser:

    return r;
}
  
bool RA_Enroll_Processor::GenerateCertsAfterRecoveryPolicy(AuthParams *login, RA_Session *session, char **&origins, char **&ktypes, 
  char *&tokenType, PKCS11Obj *pkcs11objx, int pkcs11obj_enable, 
  NameValueSet *extensions, Secure_Channel *channel, Buffer *wrapped_challenge,
  Buffer *key_check, Buffer *plaintext_challenge, char *cuid, char *msn,
  const char *final_applet_version, char *khex, const char *userid, RA_Status &o_status, 
  CERTCertificate **&certificates, int &o_certNums, char **&tokenTypes)
{
    LDAPMessage *ldapResult = NULL;
    LDAPMessage *e = NULL;
    int nEntries = 0;
    char filter[512];
    char configname[512];
    char tokenStatus[100];
    char *tokenid = NULL;
    int rc = -1;
    bool r=true;
    o_status = STATUS_NO_ERROR;
    char *origTokenType = NULL;

	const char *FN="RA_Enroll_Process::GenerateCertsAfterRecoveryPolicy";
    PR_snprintf(filter, 512, "tokenUserID=%s", userid);
    
    rc = RA::ra_find_tus_token_entries_no_vlv(filter, &ldapResult, 1);
  
    if (rc != LDAP_SUCCESS) {
        RA::Debug(LL_PER_CONNECTION,FN,
			"Cant find any tokens associated with the userid=%s. "
			"There should be at least one token.", userid);
        r = false;
        o_status = STATUS_ERROR_INACTIVE_TOKEN_NOT_FOUND;
        goto loser;
    } else {
        nEntries = RA::ra_get_number_of_entries(ldapResult);
        for (e = RA::ra_get_first_entry(ldapResult); e != NULL; e = RA::ra_get_next_entry(e)) {   
            struct berval ** attr_values = RA::ra_get_attribute_values(e, "tokenStatus");

            if ((attr_values == NULL) || (attr_values[0] == NULL)) {
                RA::Debug(LL_PER_CONNECTION,FN, "Error obtaining token status");
                r = false;
                o_status = STATUS_ERROR_BAD_STATUS;
                if (attr_values != NULL) {
                    RA::ra_free_values(attr_values);
                    attr_values = NULL;
                }
                goto loser;
            }
          
            RA::Debug(LL_PER_CONNECTION,FN, "tokenStatus = %s",
              attr_values[0]->bv_val);

            strncpy(tokenStatus, attr_values[0]->bv_val, 100);
            // free attr_values
            if (attr_values != NULL) {
              RA::ra_free_values(attr_values);
              attr_values = NULL;
            }
            tokenid = RA::ra_get_token_id(e);
            RA::Debug(LL_PER_CONNECTION,FN, "tokenID = %s", tokenid);
            int cmp_result = PL_strcasecmp(tokenid, cuid);
            free(tokenid);
            if (cmp_result == 0) {
                if (PL_strcasecmp(tokenStatus, "uninitialized") == 0 ) {
                    if (nEntries == 1) {
                        // need to do enrollment outside
                        break;
                    } else {
                        RA::Debug(LL_PER_CONNECTION,FN,
                          "There are multiple token entries for user %s.", userid);

                        if (RA::ra_tus_has_active_tokens((char *)userid) == 0) {
                            r = false;
                            o_status = STATUS_ERROR_HAS_AT_LEAST_ONE_ACTIVE_TOKEN;
                            RA::Debug(LL_PER_CONNECTION,FN, "User already has one active token.");
                            goto loser;
                        } else {
                            // 1) current token is in active state
                            // 2) there are no other active tokens for this user
                            // 3) that means the previous one is the lost one
                            // get the most recent previous token:
                            LDAPMessage *prev = RA::ra_get_next_entry(e);
                            char *reason = RA::ra_get_token_reason(prev);
                            char *lostTokenCUID = RA::ra_get_token_id(prev);

                            // if the previous one is lost, then check lost reason
                            origTokenType = PL_strdup(tokenType);
                            if (PL_strcasecmp(reason, "keyCompromise") == 0) {
                                r = ProcessRecovery(login, reason, session, origins, ktypes,
                                  tokenType, pkcs11objx, pkcs11obj_enable,
                                  extensions, channel, wrapped_challenge,
                                  key_check, plaintext_challenge, cuid, msn,
                                  final_applet_version, khex, userid,
                                  o_status, certificates, lostTokenCUID, o_certNums, tokenTypes, origTokenType); 

                                break;
                            } else if (PL_strcasecmp(reason, "onHold") == 0) {
                                // then the inactive one becomes the temp token
                                // No recovery scheme, basically we are going to
                                // do the brand new enrollment
                                PR_snprintf(configname, 512, "op.enroll.%s.temporaryToken.tokenType", tokenType);
                                char *tempTokenType = (char *)(RA::GetConfigStore()->GetConfigAsString(configname, "userKeyTemporary"));
                                RA::Debug(LL_PER_CONNECTION,FN, 
									"Token type for temporary token: %s", tempTokenType);
                                PL_strcpy(tokenType, tempTokenType);
                                r = ProcessRecovery(login, reason, session, origins, ktypes,
                                  tokenType, pkcs11objx, pkcs11obj_enable,
                                  extensions, channel, wrapped_challenge,
                                  key_check, plaintext_challenge, cuid, msn,
                                  final_applet_version, khex, userid,
                                  o_status, certificates, lostTokenCUID, o_certNums, tokenTypes, origTokenType); 

                                break;
                            } else if (PL_strcasecmp(reason, "destroyed") == 0) {
                                r = ProcessRecovery(login, reason, session, origins, ktypes,
                                  tokenType, pkcs11objx, pkcs11obj_enable,
                                  extensions, channel, wrapped_challenge,
                                  key_check, plaintext_challenge, cuid, msn,
                                  final_applet_version, khex, userid,
                                  o_status, certificates, lostTokenCUID, o_certNums, tokenTypes, origTokenType); 

                                break;
                            } else {
                                r = false;
                                o_status = STATUS_ERROR_NO_SUCH_LOST_REASON;
                                RA::Debug(LL_PER_CONNECTION,FN,
                                  "No such lost reason=%s for this cuid=%s",
                                  reason, cuid);
                                goto loser;
                            }
                        }
                    }
                } else if (strcmp(tokenStatus, "active") == 0) {
                    r = true;
                    RA::Debug(LL_PER_CONNECTION,FN,
			"This is the active token. You can re-enroll if the re-enroll=true; or renew if renew=true.");
                    if (RA::ra_allow_token_renew(cuid)) {
                        // renewal allowed instead of re-enroll
                        r = ProcessRenewal(login, session, ktypes, origins,
                                  tokenType, pkcs11objx, pkcs11obj_enable,
                                  channel,
                                  cuid, msn,
                                  final_applet_version, userid,
                                  o_status, certificates, o_certNums,
                                  tokenTypes); 
                        if (r == true) {
                            RA::Debug(LL_PER_CONNECTION,FN, "ProcessRenewal returns true");
                        } else
                            goto loser;
                    }
                    break;
                } else if (strcmp(tokenStatus, "terminated") == 0) {
                    RA::Debug(LL_PER_CONNECTION,FN,
                      "terminated token cuid=%s", cuid);
                    r = false;
                    o_status = STATUS_ERROR_CONTACT_ADMIN;
                    goto loser;
                } else if (strcmp(tokenStatus, "lost") == 0) {
                    char *reason = RA::ra_get_token_reason(e);
                    if (strcmp(reason, "keyCompromise") == 0) {
                        r = false;
                        o_status = STATUS_ERROR_UNUSABLE_TOKEN_KEYCOMPROMISE;
                        RA::Debug(LL_PER_CONNECTION,FN,
							"This token cannot be reused because it has been reported lost");
                        goto loser;
                    } else if (strcmp(reason, "onHold") == 0) {
                        if (RA::ra_tus_has_active_tokens((char *)userid) == 0) {
                            r = false;
                            o_status = STATUS_ERROR_HAS_AT_LEAST_ONE_ACTIVE_TOKEN;
                            RA::Debug(LL_PER_CONNECTION,FN,
								"User already has an active token.");
                            goto loser;
                        } else { // change it back to active token
                            r = false;
                            o_status = STATUS_ERROR_CONTACT_ADMIN;
                            RA::Debug(LL_PER_CONNECTION,FN,
				"User needs to contact administrator to report lost token (it should be put on Hold).");
                            break;
                        }
                    } else if (strcmp(reason, "destroyed") == 0) {
                        r = false;
                        RA::Debug(LL_PER_CONNECTION,FN,
							"This destroyed lost case should not be executed because the token is so damaged. It should not get here");
                        o_status = STATUS_ERROR_TOKEN_DISABLED;
                        goto loser;
                    } else {
                        RA::Debug(LL_PER_CONNECTION,FN,
							"No such lost reason=%s for this cuid=%s", reason, cuid);
                        r = false;
                        o_status = STATUS_ERROR_NO_SUCH_LOST_REASON;
                        goto loser;
                    }
                } else {
                    RA::Debug(LL_PER_CONNECTION,FN,
                      "No such token status for this cuid=%s", cuid);
                    r = false;
                    o_status = STATUS_ERROR_NO_SUCH_TOKEN_STATE;
                    goto loser;
                }
            } else { // cuid != cuid of the current token
                continue;
/*
                if (RA::ra_tus_has_active_tokens((char *)userid) == 0) {
                    r = false;
                    o_status = STATUS_ERROR_HAS_AT_LEAST_ONE_ACTIVE_TOKEN;
                    RA::Debug("RA_Enroll_Processor::GenerateCertsAfterRecoveryPolicy", "You already have one active token.");
                    goto loser;
                } else
                    continue;
*/
            }
        }
    }

 loser:
    if (origTokenType != NULL) {
        PL_strfree(origTokenType);
        origTokenType = NULL;
    }
    if (rc == 0)
        if (ldapResult != NULL)
            ldap_msgfree(ldapResult);


RA::Debug("RA_Enroll_Processor::GenerateCertsAfterRecoveryPolicy", "returning boolean = %d", r); 
    return r;
}

/*
 * cfu - check  if a cert is within the renewal grace period
 *  utilize passed in grace period values. 
 */
bool RA_Enroll_Processor::isCertRenewable(CERTCertificate *cert, int graceBefore, int graceAfter){
    PRTime timeBefore, timeAfter, now;

    //Grace period input in days
    RA::Debug("RA_Enroll_Processor::isCertRenewable","graceBefore %d graceAfter %d",graceBefore,graceAfter);
    PRTime graceBefore64, graceAfter64,microSecondsPerSecond;
    PRInt64 graceBeforeSeconds,graceAfterSeconds;

    LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);

    //Get number of microseconds in each grace period value.
    LL_I2L(graceBeforeSeconds, graceBefore * 60 * 60 * 24);
    LL_I2L(graceAfterSeconds,graceAfter * 60 * 60 * 24);

    LL_MUL(graceBefore64, microSecondsPerSecond,graceBeforeSeconds);
    LL_MUL(graceAfter64,  microSecondsPerSecond,graceAfterSeconds);

    PRTime lowerBound, upperBound;
 
    DER_DecodeTimeChoice(&timeBefore, &cert->validity.notBefore);
    DER_DecodeTimeChoice(&timeAfter, &cert->validity.notAfter);

    PrintPRTime(timeBefore,"timeBefore");
    PrintPRTime(timeAfter,"timeAfter");

    now = PR_Now();

    //Calculate lower and upper legal bounds for time
    LL_SUB(lowerBound,timeAfter, graceBefore64);
    LL_ADD(upperBound,timeAfter,graceAfter64);

    PrintPRTime(lowerBound,"lowerBound");
    PrintPRTime(now,"now");
    PrintPRTime(upperBound,"upperBound");

    if(LL_CMP(now,>=, lowerBound) && LL_CMP(now,<=,upperBound)) {
        RA::Debug("RA_Enroll_Processor::isCertRenewable","returning true!");
        return true;
    }

    RA::Debug("RA_Enroll_Processor::isCertRenewable","returning false!");

    return false;
}

/*
 * cfu
 * DoRenewal - use i_cert's serial number for renewal
 * i_cert - cert to renew
 * o_cert - cert newly issued
 */
bool RA_Enroll_Processor::DoRenewal(const char *connid, const char *profileId, CERTCertificate *i_cert,
CERTCertificate **o_cert, char *error_msg, int *error_code)
{
    RA_Status status = STATUS_NO_ERROR;
    bool r = true;
    CertEnroll *certRenewal = NULL;
    Buffer *cert = NULL;
    char *cert_string = NULL;

    error_msg[0] =0;
    *error_code=0; //assume undefined

    PRUint64 snum = DER_GetInteger(&(i_cert)->serialNumber);
    RA::Debug("RA_Enroll_Processor::DoRenewal", "begins renewal for serial number %u with profileId=%s", (int)snum, profileId);

    certRenewal = new CertEnroll();
    cert = certRenewal->RenewCertificate(snum, connid, profileId, error_msg);

    if (error_msg[0] != 0) { // We can assume a non grace period error here.
        *error_code = 1;
    }
// this is where renewal happens .. audit log for fail/ success here? 
    if (cert == NULL) {
        r = false;
        RA::Debug("RA_Enroll_Processor::DoRenewal", "Renewal failed for serial number %d", snum);
        status = STATUS_ERROR_MAC_ENROLL_PDU;
        goto loser;
    }
    RA::Debug("RA_Enroll_Processor::DoRenewal", "Renewal suceeded for serial number %d", snum);

    cert_string = (char *) cert->string();
    *o_cert = CERT_DecodeCertFromPackage((char *) cert_string, 
      (int) cert->size());
    if (o_cert != NULL) {
        char msg[2048];
        RA::ra_tus_print_integer(msg, &(o_cert[0])->serialNumber);
        RA::Debug("DoRenewal", "Received newly issued Certificate");
        RA::Debug("DoRenewal serial=", msg);
        RA::Debug("DoRenewal", "yes");
    } else {
        r = false;
    }
    free(cert_string);

loser:
    if( certRenewal != NULL ) {
        delete certRenewal;
        certRenewal = NULL;
    }
    if( cert != NULL ) {
        delete cert;
        cert = NULL;
    }
    return r;
}

#define RENEWAL_FAILURE 1
#define RENEWAL_FAILURE_GRACE 2

/*
* Renewal logic
*  1. Create Optional local TPS grace period per token profile, 
*     per token type, such as signing or encryption.
*    This grace period must match how the CA is configured. Ex:
*    op.enroll.userKey.renewal.encryption.enable=true
*    op.enroll.userKey.renewal.encryption.gracePeriod.enable=true
*    op.enroll.userKey.renewal.encryption.gracePeriod.before=30
*    op.enroll.userKey.renewal.encryption.gracePeriod.after=30
*  2. In case of a grace period failure the code will go on 
*     and attempt to renew the next certificate in the list.
*  3. In case of any other code failure, the code will abort
*     and leave the token untouched, while informing the user
*     with an error message.
*
*
*/
bool RA_Enroll_Processor::ProcessRenewal(AuthParams *login, RA_Session *session, char **&ktypes,
 char **&origins,
  char *tokenType, PKCS11Obj *pkcs11objx, int pkcs11obj_enable,
  Secure_Channel *channel,
  const char *cuid, char *msn,
  const char *final_applet_version, const char *userid,
  RA_Status &o_status, CERTCertificate **&certificates,
  int &o_certNums, char **&tokenTypes)
{
    bool r = true;
    o_status = STATUS_ERROR_RENEWAL_IS_PROCESSED;
    char keyTypePrefix[256];
    char configname[256];
    char filter[256];
    LDAPMessage *result = NULL;
    const char *pretty_cuid = NULL;
    char audit_msg[512] = "";
    char *keyVersion = NULL;
    int renewal_failure_found = 0;
   
    int   maxCertUpdate = 25; 
    char  *renewedCertUpdateList[25];
    int   renewedCertUpdateCount = 0;
    int renew_error = 0;

    int i = 0;
    const char *FN="RA_Enroll_Processor::ProcessRenewal";

    RA::Debug("RA_Enroll_Processor::ProcessRenewal", "starts");

    // get key version for audit logs
    if (channel != NULL) {
        if( keyVersion != NULL ) {
            PR_Free( (char *) keyVersion );
            keyVersion = NULL;
        }
        keyVersion = Util::Buffer2String(channel->GetKeyInfoData());
    }

    // e.g. op.enroll.userKey.renewal.keyType.num
    // renewal params will just have to match that of the previous
    // enrollment tps profile. Will try to be smarter later...
    PR_snprintf(configname, 256, "op.enroll.%s.renewal.keyType.num",
      tokenType);
    int keyTypeNum = RA::GetConfigStore()->GetConfigAsInt(configname, -1);
    if (keyTypeNum == -1) {
        RA::Debug("RA_Enroll_Processor::ProcessRenewal", "Missing the configuration parameter for %s", configname);
        r = false;
        o_status = STATUS_ERROR_DEFAULT_TOKENTYPE_PARAMS_NOT_FOUND;
        PR_snprintf(audit_msg, 512, "Missing the configuration parameter for %s", configname);
        goto loser;
    }

    RA::Debug("RA_Enroll_Processor::ProcessRenewal", "keyType.num=%d", keyTypeNum);

    o_certNums = keyTypeNum;
    certificates = (CERTCertificate **) malloc (sizeof(CERTCertificate *) * keyTypeNum);
    ktypes = (char **) malloc (sizeof(char *) * keyTypeNum);
    origins = (char **) malloc (sizeof(char *) * keyTypeNum);
    tokenTypes = (char **) malloc (sizeof(char *) * keyTypeNum);

    for (i=0; i<keyTypeNum; i++) {
        certificates[i] = NULL;
        ktypes[i] = NULL;
        origins[i] = NULL;
        tokenTypes[i] = NULL;
    }
    
    for (i=0; i<keyTypeNum; i++) {
        bool renewable = true;
        // e.g. op.enroll.userKey.renewal.keyType.value.0=signing
        // e.g. op.enroll.userKey.renewal.keyType.value.1=encryption
        PR_snprintf(configname, 256, "op.enroll.%s.renewal.keyType.value.%d", tokenType, i);
        const char *keyTypeValue = (char *)(RA::GetConfigStore()->GetConfigAsString(configname));

        if (keyTypeValue == NULL) {
            RA::Debug("RA_Enroll_Processor::ProcessRenewal",
              "Missing the configuration parameter for %s", configname);
            r = false;
            o_status = STATUS_ERROR_DEFAULT_TOKENTYPE_PARAMS_NOT_FOUND;
            PR_snprintf(audit_msg, 512, "Missing the configuration parameter for %s", configname);
            goto loser;
        }
        RA::Debug("RA_Enroll_Processor::ProcessRenewal", "keyType == %s ", keyTypeValue);
        TokenKeyType key_type = KEY_TYPE_ENCRYPTION;
        if (strcmp(keyTypeValue, "signing") == 0)
          key_type = KEY_TYPE_SIGNING;
        else if (strcmp(keyTypeValue, "encryption") == 0) 
          key_type = KEY_TYPE_ENCRYPTION;
        else
          key_type = KEY_TYPE_SIGNING_AND_ENCRYPTION;

        // e.g. op.enroll.userKey.renewal.signing.enable=true
        PR_snprintf(configname, 256, "op.enroll.%s.renewal.%s.enable", tokenType, keyTypeValue);
        renewable = RA::GetConfigStore()->GetConfigAsBool(configname);

        if (!renewable) {
           RA::Debug("RA_Enroll_Processor::ProcessRenewal", "renewal not enabled");
           continue;
        }

        // set allowable $$ config patterns
        NameValueSet nv;
        pretty_cuid = GetPrettyPrintCUID(cuid);

        nv.Add("pretty_cuid", pretty_cuid);
        nv.Add("cuid", cuid);
        nv.Add("msn", msn);
        nv.Add("userid", userid);
        //nv.Add("profileId", profileId);

        /* populate auth parameters output to nv also */
        /* so we can reference to the auth parameter by */
        /* using $auth.cn$, or $auth.mail$ */
        if (login != NULL) {
          int s = login->Size();
          for (int x = 0; x < s; x++) {
             char namebuf[2048];
             char *name = login->GetNameAt(x);
             sprintf(namebuf, "auth.%s", name);
             nv.Add(namebuf, login->GetValue(name));
          }
        }

        /*
         * Get certs from the tokendb for this token to find out about
         * renewal possibility
         */


            RA::Debug("RA_Enroll_Processor::ProcessRenewal", "Renew the certs for %s", keyTypeValue);
            PR_snprintf(filter, 256, "(&(tokenKeyType=%s)(tokenID=%s))",
              keyTypeValue, cuid);       
            int rc = RA::ra_find_tus_certificate_entries_by_order_no_vlv(filter,
              &result, 1);
 
            tokenTypes[i] = PL_strdup(tokenType);
            if (rc == LDAP_SUCCESS) {
                bool renewed = false;
                const char *caconnid;
                const char *profileId;
                PR_snprintf(keyTypePrefix, 256, "op.enroll.%s.keyGen.%s", tokenType,keyTypeValue);
                PR_snprintf(configname, 256, "op.enroll.%s.renewal.%s.enable", tokenType, keyTypeValue);
                PR_snprintf((char *)configname, 256,"op.enroll.%s.renewal.%s.certId", tokenType, keyTypeValue);
                char *certId = (char *)RA::GetConfigStore()->GetConfigAsString(configname, "C0");
                PR_snprintf((char *)configname, 256, "op.enroll.%s.renewal.%s.certAttrId", tokenType, keyTypeValue);
                char *certAttrId = (char *)RA::GetConfigStore()->GetConfigAsString(configname, "c0");
                //PR_snprintf((char *)configname, 256, "%s.privateKeyAttrId", keyTypePrefix);
                //const char *priKeyAttrId = RA::GetConfigStore()->GetConfigAsString(configname, "k0");
                //PR_snprintf((char *)configname,  256,"%s.publicKeyAttrId", keyTypePrefix);
                //const char *pubKeyAttrId = RA::GetConfigStore()->GetConfigAsString(configname, "k1");
                RA::Debug("RA_Enroll_Processor::ProcessRenewal",
                  "certId=%s, certAttrId=%s",certId, certAttrId);

                char finalCertId[3];
                char finalCertAttrId[3];

                finalCertId[0] = certId[0];
                finalCertId[1] = certId[1];
                finalCertId[2] = 0;

                finalCertAttrId[0] = certAttrId[0];
                finalCertAttrId[1] = certAttrId[1];
                finalCertAttrId[2] = 0;

                LDAPMessage *e= NULL;
                char *attr_status = NULL;
                for( e = RA::ra_get_first_entry( result );
                       e != NULL;
                       e = RA::ra_get_next_entry( e ) ) {
                    attr_status = RA::ra_get_cert_status( e );
                    if( (strcmp( attr_status, "revoked" ) == 0) ||
                        (strcmp( attr_status, "renewed" ) == 0) ) {
                        if (attr_status != NULL) {
                            PL_strfree(attr_status);
                            attr_status = NULL;
                        }
                        continue;
                    }

                    const char *label= NULL;
                    const char *pattern= NULL;
                    Buffer *certbuf = NULL;

                    // retrieve the most recent certificate to start

                    CERTCertificate **certs = RA::ra_get_certificates(e);
                    CERTCertificate *o_cert = NULL;
                    SECKEYPublicKey *pk_p = NULL;
                    SECItem si_mod;
                    Buffer *modulus=NULL;
                    SECItem *si_kid = NULL;
                    Buffer *keyid=NULL;
                    SECItem si_exp;
                    Buffer *exponent=NULL;
                    CERTSubjectPublicKeyInfo*  spkix = NULL;

                    bool graceEnabled = false;
                    int graceBefore = 0;
                    int graceAfter = 0;

                    if (certs[0] != NULL) {

                        RA::Debug("RA_Enroll_Processor::ProcessRenewal",
                          "Certificate to check for renew");

                        // check if renewable (note: CA makes the final decision)
                        /* testing...pass through for now
                        if (!isCertRenewable(certs[0])) {
                            RA::Debug("RA_Enroll_Processor::ProcessRenewal",
                                "Cert outside of renewal period");
                            r = false;
                            goto rloser;
                        }
                        */

                        // op.enroll.userKey.renewal.signing.ca.conn
                        // op.enroll.userKey.renewal.encryption.ca.conn
                        PR_snprintf(configname, 256, 
                          "op.enroll.%s.renewal.%s.ca.conn", tokenType, keyTypeValue);
                        caconnid = RA::GetConfigStore()->GetConfigAsString(configname);
                        if (caconnid == NULL) {
                            RA::Debug("RA_Enroll_Processor::ProcessRenewal",
                              "Missing the configuration parameter for %s", configname);
                              r = false;
                            o_status = STATUS_ERROR_DEFAULT_TOKENTYPE_PARAMS_NOT_FOUND;
                            PR_snprintf(audit_msg, 512, "Missing the configuration parameter for %s", configname);
                            goto rloser;
                        }
                        
                        // op.enroll.userKey.renewal.signing.ca.profileId
                        // op.enroll.userKey.renewal.encryption.ca.profileId
                        PR_snprintf(configname, 256, 
                          "op.enroll.%s.renewal.%s.ca.profileId", tokenType, keyTypeValue);
                        profileId = RA::GetConfigStore()->GetConfigAsString(configname);
                        if (profileId == NULL) {
                            RA::Debug("RA_Enroll_Processor::ProcessRenewal",
                              "Missing the configuration parameter for %s", configname);
                              r = false;
                            o_status = STATUS_ERROR_DEFAULT_TOKENTYPE_PARAMS_NOT_FOUND;
                            PR_snprintf(audit_msg, 512, "Missing the configuration parameter for %s", configname);
                            goto rloser;
                        }

                        RA::Debug("RA_Enroll_Processor::ProcessRenewal","got profileId=%s",profileId);
			RA::Debug("RA_Enroll_Processor::ProcessRenewal", "begin renewal");


                        PR_snprintf(configname,256,
                           "op.enroll.%s.renewal.%s.gracePeriod.enable",tokenType,keyTypeValue);

                        graceEnabled = RA::GetConfigStore()->GetConfigAsBool(configname,0);

                        if(graceEnabled) {

                            PR_snprintf(configname,256,
                               "op.enroll.%s.renewal.%s.gracePeriod.before",tokenType,keyTypeValue);

                            graceBefore = RA::GetConfigStore()->GetConfigAsInt(configname,0);

                            PR_snprintf(configname,256,
                                "op.enroll.%s.renewal.%s.gracePeriod.after",tokenType,keyTypeValue); 
                            
                            graceAfter = RA::GetConfigStore()->GetConfigAsInt(configname,0); 
                            // check if renewable (note: CA makes the final decision)
                            if (!isCertRenewable(certs[0],graceBefore,graceAfter)) {
                                RA::Debug("RA_Enroll_Processor::ProcessRenewal",
                                    "Cert outside of renewal period");
                                renewal_failure_found = RENEWAL_FAILURE_GRACE;
                                //Since this is merely a grace period failure for one cert
                                //let's keep going.
                                r = true;
                                goto rloser;
                            }

                        }

                        // send renewal request to CA
                        // o_cert is the cert gotten back
                        r = DoRenewal(caconnid, profileId, certs[0], &o_cert, audit_msg, &renew_error);
                        if (r == false) {
			    RA::Debug("RA_Enroll_Processor::ProcessRenewal", "after DoRenewal failure. o_cert %p renew_error %d",o_cert,renew_error);
                            o_status = STATUS_ERROR_MAC_ENROLL_PDU;
                            //Assume a renewal grace failure here since we can't obtain the reason.
                            //This is the most likely error and there is a chance the next renewal may succeed.
                            if ( renew_error == 0) { //Assume undefined error is error coming from CA
                                renewal_failure_found = RENEWAL_FAILURE_GRACE;
                            } else {
                                renewal_failure_found = RENEWAL_FAILURE;
                            }
                            char snum[2048];
                            RA::ra_tus_print_integer(snum, &(certs[0])->serialNumber);
                            RA::Audit(EV_RENEWAL, AUDIT_MSG_PROC_CERT_REQ, 
                              userid, cuid, msn, "failure", "renewal", final_applet_version,
                              keyVersion != NULL ? keyVersion :  "", 
                              snum, caconnid, audit_msg);
                            //Since this is merely a grace period or renewal failure for one cert
                            //let's keep it going

                            if (renew_error == 0) { //undefined error means probably grace period, forgive that.
                                r = true;
                            }
                            goto rloser;
                        }

                        // got cert... 

                        // build label
                        PR_snprintf((char *)configname, 256, "%s.%s.keyGen.%s.label",
	                    OP_PREFIX, tokenType, keyTypeValue);
                        RA::Debug(LL_PER_CONNECTION,FN,
		                "label '%s'", configname);
                        pattern = RA::GetConfigStore()->GetConfigAsString(configname);

                        if(pattern == NULL)
                        {
                            RA::Debug("RA_Enroll_Processor::ProcessRenewal", "no configured cert label!");
                            renewal_failure_found = RENEWAL_FAILURE;
                            PR_snprintf(audit_msg,512, "No cert label configured for cert!");
                            goto rloser;
                        }

                        RA::Debug(LL_PER_CONNECTION,FN,
                                "pattern '%s'",pattern);

			label = MapPattern(&nv, (char *) pattern);

                        RA::Debug(LL_PER_CONNECTION,FN,
                                "label '%s'",label);

			if (o_cert != NULL) {
			  RA::Debug("RA_Enroll_Processor::ProcessRenewal", "got cert!!");
//			  tmp_c = NSSBase64_EncodeItem(0, 0, 0, &(o_cert)->derCert);
//			  RA::Debug("RA_Enroll_Processor::ProcessRenewal", "after NSSBase64_EncodeItem");

                          char snum[2048];
                          RA::ra_tus_print_integer(snum, &o_cert->serialNumber);
                          RA::Audit(EV_RENEWAL, AUDIT_MSG_PROC_CERT_REQ, 
                            userid, cuid, msn, "success", "renewal", final_applet_version, 
                            keyVersion != NULL ? keyVersion :  "", 
                            snum, caconnid, "certificate renewed");
			} else {
			  RA::Debug("RA_Enroll_Processor::ProcessRenewal", "no cert!!");
                          PR_snprintf(audit_msg, 512, "No cert returned from DoRenewal");
			  goto rloser;
			}

                        ktypes[i] = PL_strdup(keyTypeValue);
                        origins[i] = PL_strdup(cuid);
                        certificates[i] = o_cert;
                        //o_certNums++;

                        // For the encrytion cert we actually need to calculate the proper certId and certAttrId
                        // since we now leave previous encryption certs on the token to allow dencryption of old
                        // Emails by the user.
             
                        if( key_type == KEY_TYPE_ENCRYPTION) {

                            int new_cert_id = GetNextFreeCertIdNumber(pkcs11objx);

                            RA::Debug("RA_Enroll_Processor::ProcessRenewal", 
                                "Encryption cert, calculated new cert id: %d",new_cert_id);

                            //Is the calculated cert id reasonable based on the current state of the
                            // token and the expected renewal configuration.
                            if( !(new_cert_id  > keyTypeNum ) || new_cert_id > 9) {
                                RA::Debug(LL_PER_CONNECTION,FN,
                                    "RA_Enroll_Processor::ProcessRenewal","Possible misconfiguration or out of sync token!");
                                PR_snprintf(audit_msg, 512, "Renewal of cert failed, misconfiguration or out of sync token!");
                                renewal_failure_found = RENEWAL_FAILURE; 
                                goto rloser;

                            }

                            finalCertId[0]= 'C';
                            finalCertId[1] = '0' + new_cert_id;
                       
                            finalCertAttrId[0] = 'c';
                            finalCertAttrId[1] = '0' + new_cert_id;

                            RA::Debug(LL_PER_CONNECTION,FN,
                                 "finalCertId %s finalCertAttrId %s", finalCertId, finalCertAttrId);
                        }

                        // write certificate to token
			certbuf = new Buffer(o_cert->derCert.data, o_cert->derCert.len);
                        if (pkcs11obj_enable)
			{
			  ObjectSpec *objSpec = 
			    ObjectSpec::ParseFromTokenData(
							   (finalCertId[0] << 24) +
							   (finalCertId[1] << 16),
							   certbuf);
			  pkcs11objx->AddObjectSpec(objSpec);
			} else {
                          RA::Debug(LL_PER_CONNECTION,FN,
                            "Not implemented");
                          renewal_failure_found = RENEWAL_FAILURE;
                          PR_snprintf(audit_msg, 512, "Write cert to token failed: pkcs11obj_enable = false not implemented");
                          goto rloser;
/*
                          RA::Debug(LL_PER_CONNECTION,FN,
                                 "About to create certificate object on token");
                          rc = channel->CreateCertificate(certId, certbuf);
                          if (rc == -1) {
                                 RA::Error(LL_PER_CONNECTION,FN,
                                 "Failed to create certificate object on token");

                                 o_status = STATUS_ERROR_MAC_ENROLL_PDU;
                                 goto rloser;
                          }
*/
                        }

                        if (o_cert->subjectKeyID.data != NULL) {
			  RA::Debug("RA_Enroll_Processor::ProcessRenewal", "subjectKeyID found in cert");
//later, add code to check if keys really exist on token!
                          keyid = new Buffer((BYTE*)o_cert->subjectKeyID.data,
                                    (unsigned int)o_cert->subjectKeyID.len);

                        } else {// should always have keyid
//use existing original keyid
			  RA::Debug("RA_Enroll_Processor::ProcessRenewal", "no subjectKeyID found in cert, use existing");
                          keyid = new Buffer((BYTE*)certs[0]->subjectKeyID.data,
                                    (unsigned int)certs[0]->subjectKeyID.len);
                        }

                        if (pkcs11obj_enable)
			{
			  Buffer b = channel->CreatePKCS11CertAttrsBuffer(
                               key_type , finalCertAttrId, label, keyid);
                          if (b == NULL) {
                              PR_snprintf(audit_msg, 512, "Write cert to token failed: CreatePKCS11CertAttrsBuffer returns null");
                              renewal_failure_found = RENEWAL_FAILURE;
                              goto rloser;
                          }
                          ObjectSpec *objSpec = 
                              ObjectSpec::ParseFromTokenData(
				   (finalCertAttrId[0] << 24) +
				   (finalCertAttrId[1] << 16),
				   &b);
                          if (objSpec == NULL) {
                              PR_snprintf(audit_msg, 512, "Write cert to token failed: ParseFromTokenData returns null");
                              renewal_failure_found = RENEWAL_FAILURE;
                              goto rloser;
                          }

                          //We need to massage the fixedAttributes of this object to allow the CKA_ID value
                          //of the original encryption cert to be available for coolkey to read.
                          // Coolkey only deals in a one byte index 0 - n, ex: "01".
                          // Coolkey uses the final byte of the "fixedAttributes" property of each object
                          // to identify the object. This value needs to be the same for each cert and its
                          // corresponding key pair. See ObjectSpec::ParseAttributes.

                          if (key_type == KEY_TYPE_ENCRYPTION) {

                             unsigned long currentFixedAttributes = objSpec->GetFixedAttributes();
                             unsigned long modifiedFixedAttributes = currentFixedAttributes;

                             // Here we want the original encryption cert's id number.
                             int val = (certId[1] - '0');

                             modifiedFixedAttributes &= (BYTE) 0xFFFFFFF0;
                             modifiedFixedAttributes |=  (BYTE) val;
                             objSpec->SetFixedAttributes(modifiedFixedAttributes);
 
                             RA::Debug("RA_Enroll_Processor::ProcessRenewal", 
                                 "original fixed Attributes %lu  modified ones %lu",
                                 currentFixedAttributes,modifiedFixedAttributes);  
                          }

			  pkcs11objx->AddObjectSpec(objSpec);
			} else {
                          RA::Debug(LL_PER_CONNECTION,FN,
                            "Not implemented");
                          PR_snprintf(audit_msg, 512, "Write cert to token failed: pkcs11obj_enable = false not implemented");
                          renewal_failure_found = RENEWAL_FAILURE;
                          goto rloser;
/*
                          RA::Debug(LL_PER_CONNECTION,FN,
                                  "About to create PKCS#11 certificate Attributes");
                          rc = channel->CreatePKCS11CertAttrs(keyTypeValue, certAttrId, label, keyid);
                          if (rc == -1) {
                           RA::Error(LL_PER_CONNECTION,FN,
                                  "PKCS11 Certificate attributes creation failed");
                                  o_status = STATUS_ERROR_MAC_ENROLL_PDU;
                                  goto rloser;
                          }
*/
                        }

                        spkix = &(o_cert->subjectPublicKeyInfo);
                        if (spkix == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: subjectPublicKeyInfo is null");
                            goto rloser;
                        }
                        pk_p = SECKEY_ExtractPublicKey(spkix);
                        if (pk_p == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: ExtractPublicKey is null");
                            goto rloser;
                        }
                        SECKEY_DestroySubjectPublicKeyInfo(spkix);

			/* fill in keyid, modulus, and exponent */

			si_mod = pk_p->u.rsa.modulus;
			modulus = new Buffer((BYTE*) si_mod.data, si_mod.len);
                        if (modulus == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: modulus is null");
                            renewal_failure_found = RENEWAL_FAILURE;
                            goto rloser;
                        }
			spkix = SECKEY_CreateSubjectPublicKeyInfo(pk_p);
                        if (spkix == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: CreateSubjectPublicKeyInfo returns null");
                            renewal_failure_found = RENEWAL_FAILURE;
                            goto rloser;
                        }

			/* 
			 * RFC 3279
			 * The keyIdentifier is composed of the 160-bit SHA-1 hash of the
			 * value of the BIT STRING subjectPublicKey (excluding the tag,
			 * length, and number of unused bits).
			 */
			spkix->subjectPublicKey.len >>= 3;
			si_kid = PK11_MakeIDFromPubKey(&spkix->subjectPublicKey);
                        if (si_kid == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: si_kid is null");
                            renewal_failure_found = RENEWAL_FAILURE;
                            goto rloser;
                        }
			spkix->subjectPublicKey.len <<= 3;
			SECKEY_DestroySubjectPublicKeyInfo(spkix);

                        if (keyid == NULL)
			    keyid = new Buffer((BYTE*) si_kid->data, si_kid->len);
                        if (keyid == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: keyid is null");
                            renewal_failure_found = RENEWAL_FAILURE;
                            goto rloser;
                        }
			si_exp = pk_p->u.rsa.publicExponent;
			exponent =  new Buffer((BYTE*) si_exp.data, si_exp.len);
                        if (exponent == NULL) {
                            PR_snprintf(audit_msg, 512, "Write cert to token failed: exponent is null");
                            renewal_failure_found = RENEWAL_FAILURE;
                            goto rloser;
                        }
			RA::Debug(LL_PER_PDU, "RA_Enroll_Processor::Process",
              "Keyid, modulus and exponent have been extracted from public key");

                        renewed = true;

                        RA::Audit(EV_RENEWAL, AUDIT_MSG_PROC,
                          userid != NULL ? userid : "",
                          cuid != NULL ? cuid : "",
                          msn != NULL ? msn : "",
                          "success",
                          "renewal",
                          final_applet_version != NULL ? final_applet_version : "",
                          keyVersion != NULL? keyVersion : "",
                          "Cert written to token successfully");


		    rloser:

                        if( keyid != NULL ) {
                          delete keyid;
                          keyid = NULL;
                        }
			if( label != NULL ) {
			  PL_strfree( (char *) label );
			  label = NULL;
			}
                        if(renewal_failure_found == RENEWAL_FAILURE) {
                            RA::Debug("RA_Enroll_Processor_ProcessRenewal", "A renewal in list failed other than grace period error, aborting.");
                            goto loser;
                        }
                    }
                    break;
                  } //for
                  if((strcmp( attr_status, "active" ) == 0) &&
                       renewed) {
                      char *cn = RA::ra_get_cert_cn(e);
                      if(renewedCertUpdateCount < ( maxCertUpdate -1)) //unlikely scenario this fails 
                          renewedCertUpdateList[renewedCertUpdateCount++] = PL_strdup(cn);
                      // Let's hold off on the celebration until the end.
                      // RA::ra_update_cert_status(cn, "renewed");
                      if (cn != NULL) {
                          PL_strfree(cn);
                          cn = NULL;
                      }
                  }
                  if( attr_status != NULL ) {
                      PL_strfree( attr_status );
                      attr_status = NULL;
                  }
            } else {
	      r = false;
	      o_status = STATUS_ERROR_LDAP_CONN;
	      goto loser;
            }
            RA::Debug("RA_Enroll_Processor::ProcessRenewal", 
		      "Filter to find certificates = %s", filter);
    }

loser:
    if (strlen(audit_msg) > 0) { // a failure occurred
        RA::Audit(EV_RENEWAL, AUDIT_MSG_PROC,
          userid != NULL ? userid : "",
          cuid != NULL ? cuid : "",
          msn != NULL ? msn : "",
          "failure",
          "renewal",
          final_applet_version != NULL ? final_applet_version : "",
          keyVersion != NULL? keyVersion : "",
          audit_msg);
    }

    //Let's wait until all the certs are processed to actually update the renewal status
    RA::Debug("RA_Enroll_Process::ProcessRenewal","renewedCertUpdateCount %d", renewedCertUpdateCount);
    if(renewedCertUpdateCount > 0) {
        for(int rr = 0; rr < renewedCertUpdateCount; rr++) {
            if(renewedCertUpdateList[rr]) {
                if(renewal_failure_found != RENEWAL_FAILURE) {
                    RA::Debug("RA_Enroll_Process::ProcessRenewal","updating to renewed status of cn= %s", renewedCertUpdateList[rr]);
                    RA::ra_update_cert_status(renewedCertUpdateList[rr],"renewed");
                }
                PL_strfree(renewedCertUpdateList[rr]);
                renewedCertUpdateList[rr] = NULL;
            }
        }
    } else {
        // All certs failed to renew 
         RA::Debug("RA_Enroll_Process::ProcessRenewal","All certs failed to renew, bailing with error");
        o_status =  STATUS_ERROR_MAC_ENROLL_PDU;
        r = false;

    }

    if( pretty_cuid != NULL ) {
        PR_Free( (char *) pretty_cuid );
        pretty_cuid = NULL;
    }
    if( result != NULL ) {
        ldap_msgfree( result );
    }
  
    if( keyVersion != NULL ) {
        PR_Free( (char *) keyVersion );
        keyVersion = NULL;
    }

    return r;
}

bool RA_Enroll_Processor::ProcessRecovery(AuthParams *login, char *reason, RA_Session *session, char **&origins, char **&ktypes,
  char *tokenType, PKCS11Obj *pkcs11objx, int pkcs11obj_enable,
  NameValueSet *extensions, Secure_Channel *channel, Buffer *wrapped_challenge,
  Buffer *key_check, Buffer *plaintext_challenge, char *cuid, char *msn,
  const char *final_applet_version, char *khex, const char *userid,
  RA_Status &o_status, CERTCertificate **&certificates, char *lostTokenCUID,