OSDN Git Service

* Bug Fix.
[modchxj/mod_chxj.git] / src / mod_chxj.c
1 /*
2  * Copyright (C) 2005-2008 Atsushi Konno All rights reserved.
3  * Copyright (C) 2005 QSDN,Inc. All rights reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 #include <unistd.h>
18 #include <string.h>
19 #include <limits.h>
20 #include <errno.h>
21
22 #include "httpd.h"
23 #include "http_config.h"
24 #include "http_core.h"
25 #include "http_protocol.h"
26 #include "http_log.h"
27 #include "ap_config.h"
28 #include "apr_strings.h"
29 #include "util_filter.h"
30 #include "apr_buckets.h"
31 #include "apr_lib.h"
32 #include "apr_tables.h"
33 #include "apr_dso.h"
34 #include "apr_general.h"
35 #include "apr_pools.h"
36
37 #include "mod_chxj.h"
38 #include "chxj_encoding.h"
39 #include "qs_ignore_sp.h"
40 #include "qs_log.h"
41 #include "qs_malloc.h"
42 #include "qs_parse_attr.h"
43 #include "qs_parse_file.h"
44 #include "qs_parse_string.h"
45 #include "qs_parse_tag.h"
46 #include "chxj_load_device_data.h"
47 #include "chxj_load_emoji_data.h"
48 #include "chxj_specified_device.h"
49 #include "chxj_tag_util.h"
50 #include "chxj_xhtml_mobile_1_0.h"
51 #include "chxj_hdml.h"
52 #include "chxj_chtml10.h"
53 #include "chxj_chtml20.h"
54 #include "chxj_chtml30.h"
55 #include "chxj_chtml40.h"
56 #include "chxj_chtml50.h"
57 #include "chxj_jhtml.h"
58 #include "chxj_jxhtml.h"
59 #include "chxj_img_conv_format.h"
60 #include "chxj_qr_code.h"
61 #include "chxj_encoding.h"
62 #include "chxj_apply_convrule.h"
63 #include "chxj_cookie.h"
64 #include "chxj_url_encode.h"
65 #include "chxj_str_util.h"
66 #if defined(USE_MYSQL_COOKIE)
67 #  include "chxj_mysql.h"
68 #endif
69 #include "chxj_serf.h"
70
71
72 #define CHXJ_VERSION_PREFIX PACKAGE_NAME "/"
73 #define CHXJ_VERSION        PACKAGE_VERSION
74 #define CHXJ_POST_MAX       (0x1000000)
75
76 converter_t convert_routine[] = {
77   {
78     /* CHXJ_SPEC_UNKNOWN          */
79     .converter = NULL,
80     .encoder  = NULL,
81   },
82   {
83     /* CHXJ_SPEC_Chtml_1_0        */
84     .converter = chxj_convert_chtml10,
85     .encoder  = chxj_encoding,
86   },
87   {
88     /* CHXJ_SPEC_Chtml_2_0        */
89     .converter = chxj_convert_chtml20,
90     .encoder  = chxj_encoding,
91   },
92   {
93     /* CHXJ_SPEC_Chtml_3_0        */
94     .converter = chxj_convert_chtml30,
95     .encoder  = chxj_encoding,
96   },
97   {
98     /* CHXJ_SPEC_Chtml_4_0        */
99     .converter = chxj_convert_chtml40,
100     .encoder  = chxj_encoding,
101   },
102   {
103     /* CHXJ_SPEC_Chtml_5_0        */
104     .converter = chxj_convert_chtml50,
105     .encoder  = chxj_encoding,
106   },
107   {
108     /* CHXJ_SPEC_Chtml_6_0        */
109     .converter = chxj_convert_chtml50,
110     .encoder  = chxj_encoding,
111   },
112   {
113     /* CHXJ_SPEC_Chtml_7_0        */
114     .converter = chxj_convert_chtml50,
115     .encoder  = chxj_encoding,
116   },
117   {
118     /* CHXJ_SPEC_XHtml_Mobile_1_0 */
119     .converter = chxj_convert_xhtml_mobile_1_0,
120     .encoder  = chxj_encoding,
121   },
122   {
123     /* CHXJ_SPEC_Hdml             */
124     .converter = chxj_convert_hdml,
125     .encoder  = chxj_encoding,
126   },
127   {
128     /* CHXJ_SPEC_Jhtml            */
129     .converter = chxj_convert_jhtml,
130     .encoder  = chxj_encoding,
131   },
132   {
133     /* CHXJ_SPEC_Jxhtml            */
134     .converter = chxj_convert_jxhtml,
135     .encoder  = chxj_encoding,
136   },
137   {
138     /* CHXJ_SPEC_HTML             */
139     .converter = NULL,
140     .encoder  = NULL,
141   },
142 };
143
144 static int chxj_convert_input_header(request_rec *r,chxjconvrule_entry *entryp);
145 static void s_add_cookie_id_if_has_location_header(request_rec *r, cookie_t *cookie);
146 static void s_clear_cookie_header(request_rec *r, device_table *spec);
147
148 /**
149  * Only when User-Agent is specified, the User-Agent header is camouflaged. 
150  *
151  * @param r   [i]
152  */
153 static apr_status_t 
154 chxj_headers_fixup(request_rec *r)
155 {
156   mod_chxj_config*    dconf; 
157   chxjconvrule_entry* entryp;
158   char*               user_agent;
159   device_table*       spec;
160   char                *contentType;
161   char                *contentLength;
162
163   DBG(r, "start chxj_headers_fixup()");
164   dconf = chxj_get_module_config(r->per_dir_config, &chxj_module);
165
166   user_agent = (char*)apr_table_get(r->headers_in, HTTP_USER_AGENT);
167   spec = chxj_specified_device(r, user_agent);
168
169   contentType = (char *)apr_table_get(r->headers_in, "Content-Type");
170   if (contentType
171       && strncasecmp("multipart/form-data", contentType, 19) == 0) {
172     DBG(r, "detect multipart/form-data ==> no target");
173     DBG(r, "end chxj_headers_fixup()");
174     return DECLINED;
175   }
176   if (r->method_number == M_POST) {
177     if (!apr_table_get(r->headers_in, "X-Chxj-Forward")) {
178       s_clear_cookie_header(r, spec);
179     }
180   }
181   else {
182     s_clear_cookie_header(r, spec);
183   }
184
185   switch(spec->html_spec_type) {
186   case CHXJ_SPEC_Chtml_1_0:
187   case CHXJ_SPEC_Chtml_2_0:
188   case CHXJ_SPEC_Chtml_3_0:
189   case CHXJ_SPEC_Chtml_4_0:
190   case CHXJ_SPEC_Chtml_5_0:
191   case CHXJ_SPEC_Chtml_6_0:
192   case CHXJ_SPEC_Chtml_7_0:
193   case CHXJ_SPEC_XHtml_Mobile_1_0:
194   case CHXJ_SPEC_Hdml:
195   case CHXJ_SPEC_Jhtml:
196   case CHXJ_SPEC_Jxhtml:
197     entryp = chxj_apply_convrule(r, dconf->convrules);
198     if (! entryp) {
199       DBG(r, "end chxj_headers_fixup() no pattern");
200       return DECLINED;
201     }
202     if (!entryp || !(entryp->action & CONVRULE_ENGINE_ON_BIT)) {
203       DBG(r,"EngineOff");
204       return DECLINED;
205     }
206   
207     apr_table_setn(r->headers_in, 
208                    CHXJ_HTTP_USER_AGENT, 
209                    user_agent);
210   
211     if (entryp->user_agent)
212       apr_table_setn(r->headers_in, 
213                      HTTP_USER_AGENT, 
214                      entryp->user_agent);
215
216     chxj_convert_input_header(r,entryp);
217
218     break;
219   
220   default:
221     return DECLINED;
222
223   }
224
225
226   if (r->method_number == M_POST) {
227     if (! apr_table_get(r->headers_in, "X-Chxj-Forward")) {
228         DBG(r, "set Input handler old:[%s] proxyreq:[%d] uri:[%s] filename:[%s]", r->handler, r->proxyreq, r->uri, r->filename);
229         r->proxyreq = PROXYREQ_NONE;
230         r->handler = apr_psprintf(r->pool, "chxj-input-handler");
231     }
232     else {
233       char *client_ip = (char *)apr_table_get(r->headers_in, CHXJ_HEADER_ORIG_CLIENT_IP);
234       if (client_ip) {
235         apr_sockaddr_t *address = NULL;
236         apr_status_t rv = apr_sockaddr_info_get(&address, ap_get_server_name(r), APR_UNSPEC, ap_get_server_port(r), 0, r->pool);
237         if (rv != APR_SUCCESS) {
238           char buf[256];
239           ERR(r, "%s:%d apr_sockaddr_info_get() failed: rv:[%d|%s]", APLOG_MARK, rv, apr_strerror(rv, buf, 256));
240           DBG(r, "end chxj_headers_fixup()");
241           return DECLINED;
242         }
243         char *addr;
244         if (dconf->forward_server_ip) {
245           addr = dconf->forward_server_ip;
246         }
247         else {
248           apr_sockaddr_ip_get(&addr, address);
249         }
250         DBG(r, "Client IP:[%s] vs Orig Client IP:[%s] vs Server IP:[%s]", r->connection->remote_ip, client_ip, addr);
251         if (strcmp(addr, r->connection->remote_ip) == 0) {
252           r->connection->remote_ip = apr_pstrdup(r->connection->pool, client_ip);
253         }
254         if (! apr_table_get(r->headers_in, "Content-Length")) {
255           contentLength = (char *)apr_table_get(r->headers_in, "X-Chxj-Content-Length");
256           if (contentLength) {
257             apr_table_set(r->headers_in, "Content-Length", contentLength);
258           }
259         }
260       }
261     }
262   }
263
264   DBG(r, "end chxj_headers_fixup()");
265
266   return DECLINED;
267 }
268
269
270 static void
271 s_clear_cookie_header(request_rec *r, device_table *spec)
272 {
273   switch(spec->html_spec_type) {
274   case CHXJ_SPEC_Chtml_1_0:
275   case CHXJ_SPEC_Chtml_2_0:
276   case CHXJ_SPEC_Chtml_3_0:
277   case CHXJ_SPEC_Chtml_4_0:
278   case CHXJ_SPEC_Chtml_5_0:
279   case CHXJ_SPEC_Chtml_6_0:
280   case CHXJ_SPEC_Chtml_7_0:
281   case CHXJ_SPEC_XHtml_Mobile_1_0:
282   case CHXJ_SPEC_Jhtml:
283     apr_table_unset(r->headers_in, "Cookie");
284     break;
285   default:
286     break;
287   }
288 }
289
290
291 /**
292  * It converts it from CHTML into XXML corresponding to each model. 
293  *
294  * @param r   [i]
295  * @param src [i]   It is former HTML character string. 
296  * @param len [i/o] It is length of former HTML character string. 
297  */
298 static char * 
299 chxj_convert(request_rec *r, const char **src, apr_size_t *len, device_table *spec, const char *ua, cookie_t **cookiep)
300 {
301   char                *user_agent;
302   char                *dst;
303   char                *tmp;
304   cookie_t            *cookie;
305   mod_chxj_config     *dconf; 
306   chxjconvrule_entry  *entryp;
307
308   DBG(r,"start of chxj_convert() input:[%.*s]", (int)*len, *src);
309   dst  = apr_pstrcat(r->pool, (char *)*src, NULL);
310
311   dconf = chxj_get_module_config(r->per_dir_config, &chxj_module);
312
313
314   entryp = chxj_apply_convrule(r, dconf->convrules);
315
316   if (!entryp || !(entryp->action & CONVRULE_ENGINE_ON_BIT))
317     return (char *)*src;
318
319
320   /*------------------------------------------------------------------------*/
321   /* get UserAgent from http header                                         */
322   /*------------------------------------------------------------------------*/
323   if (entryp->user_agent)
324     user_agent = (char *)apr_table_get(r->headers_in, CHXJ_HTTP_USER_AGENT);
325   else
326     user_agent = (char *)apr_table_get(r->headers_in, HTTP_USER_AGENT);
327
328   DBG(r,"User-Agent:[%s]", user_agent);
329   DBG(r,"content type is %s", r->content_type);
330
331
332   if (! STRNCASEEQ('t','T', "text/html", r->content_type, sizeof("text/html")-1)
333   &&  ! STRNCASEEQ('a','A', "application/xhtml+xml", r->content_type, sizeof("application/xhtml+xml")-1)) {
334     DBG(r,"no convert. content type is %s", r->content_type);
335     DBG(r,"end of chxj_convert()");
336     return (char *)*src;
337   }
338
339   if (ua && user_agent && strcasecmp(user_agent, ua) != 0) {
340     /* again */
341     spec = chxj_specified_device(r, user_agent);
342   }
343
344   /*
345    * save cookie.
346    */
347   cookie = NULL;
348   if (entryp->action & CONVRULE_COOKIE_ON_BIT) {
349     switch(spec->html_spec_type) {
350     case CHXJ_SPEC_Chtml_1_0:
351     case CHXJ_SPEC_Chtml_2_0:
352     case CHXJ_SPEC_Chtml_3_0:
353     case CHXJ_SPEC_Chtml_4_0:
354     case CHXJ_SPEC_Chtml_5_0:
355     case CHXJ_SPEC_Chtml_6_0:
356     case CHXJ_SPEC_Chtml_7_0:
357     case CHXJ_SPEC_XHtml_Mobile_1_0:
358     case CHXJ_SPEC_Jhtml:
359       cookie = chxj_save_cookie(r);
360       break;
361     default:
362       break;
363     }
364   }
365
366   if (!r->header_only) {
367
368     tmp = NULL;
369     if (convert_routine[spec->html_spec_type].encoder)
370       tmp = convert_routine[spec->html_spec_type].encoder(r, 
371                                                           *src, 
372                                                           (apr_size_t *)len);
373
374     if (convert_routine[spec->html_spec_type].converter) {
375       if (tmp)
376         dst = convert_routine[spec->html_spec_type].converter(r, 
377                                                               spec, 
378                                                               tmp, 
379                                                               *len, 
380                                                               len, 
381                                                               entryp, 
382                                                               cookie);
383       else
384         dst = convert_routine[spec->html_spec_type].converter(r,
385                                                               spec, 
386                                                               tmp, 
387                                                               *len, 
388                                                               len, 
389                                                               entryp, 
390                                                               cookie);
391     }
392   }
393   ap_set_content_length(r, *len);
394
395   if (*len == 0) {
396     dst = apr_psprintf(r->pool, "\n");
397     *len = 1;
398   }
399   dst[*len] = 0;
400   if (cookie) {
401     *cookiep = cookie;
402   }
403
404   DBG(r, "end of chxj_convert()");
405
406   return dst;
407 }
408
409
410 /**
411  * It converts it from HEADER.
412  *
413  * @param r   [i]
414  */
415 static int
416 chxj_convert_input_header(request_rec *r,chxjconvrule_entry *entryp) 
417 {
418
419   char       *buff;
420   char       *buff_pre;
421   apr_size_t urilen;
422   char       *result;
423   char       *pair;
424   char       *name;
425   char       *value;
426   char       *pstate;
427   char       *vstate;
428   cookie_t   *cookie;
429   int        no_update_flag = 0;
430
431   DBG(r, "start chxj_convert_input_header()");
432
433   if (! r->args) {
434     DBG(r, "r->args=[null]");
435     DBG(r, "end   chxj_convert_input_header()");
436     return 0;
437   }
438   urilen = strlen(r->args);
439
440   result = qs_alloc_zero_byte_string(r->pool);
441
442   buff_pre = apr_pstrdup(r->pool, r->args);
443
444   for (;;) {
445     char *pair_sv;
446
447     pair = apr_strtok(buff_pre, "&", &pstate);
448     if (pair == NULL)
449       break;
450
451     buff_pre = NULL;
452
453     pair_sv = apr_pstrdup(r->pool, pair);
454
455     name  = apr_strtok(pair, "=", &vstate);
456     value = apr_strtok(NULL, "=", &vstate);
457     if (! name) continue;
458     if (strcasecmp(name, CHXJ_COOKIE_NOUPDATE_PARAM) == 0 || strcasecmp(name, chxj_url_encode(r->pool, CHXJ_COOKIE_NOUPDATE_PARAM)) == 0) {
459       DBG(r, "found cookie no update parameter");
460       no_update_flag++;
461     }
462   }
463
464   buff = apr_pstrdup(r->pool, r->args);
465   DBG(r, "r->args=[%s]", buff);
466
467   /* _chxj_dmy */
468   /* _chxj_c_ */
469   /* _chxj_r_ */
470   /* _chxj_s_ */
471   for (;;) {
472     char *pair_sv;
473
474     pair = apr_strtok(buff, "&", &pstate);
475     if (pair == NULL)
476       break;
477
478     buff = NULL;
479
480     pair_sv = apr_pstrdup(r->pool, pair);
481
482     name  = apr_strtok(pair, "=", &vstate);
483     value = apr_strtok(NULL, "=", &vstate);
484     if (! name) continue;
485     if (strncasecmp(name, "_chxj", 5) != 0 && strncasecmp(name, "%5Fchxj", sizeof("%5Fchxj")-1) != 0) {
486       if (strlen(result) != 0) 
487         result = apr_pstrcat(r->pool, result, "&", NULL);
488
489       if (strcasecmp(entryp->encoding, "NONE") != 0) {
490         apr_size_t dlen;
491         char *dvalue;
492         char *dname;
493
494         if (value && *value != 0) {
495           value = chxj_url_decode(r->pool, value);
496           dlen   = strlen(value);
497           DBG(r, "************ before encoding[%s]", value);
498   
499           dvalue = chxj_rencoding(r, value, &dlen);
500           dvalue = chxj_url_encode(r->pool, dvalue);
501   
502           DBG(r, "************ after encoding[%s]", dvalue);
503         }
504         else {
505           dvalue = "";
506         }
507
508         if (name && *name != 0) {
509           name = chxj_url_decode(r->pool, name);
510           dlen = strlen(name);
511           dname = chxj_rencoding(r, name, &dlen);
512           dname = chxj_url_encode(r->pool, dname);
513         }
514         else {
515           dname = "";
516         }
517
518         result = apr_pstrcat(r->pool, result, dname, "=", dvalue, NULL);
519       }
520       else {
521         if (strcmp(name, pair_sv) != 0)
522           result = apr_pstrcat(r->pool, result, name, "=", value, NULL);
523         else
524           result = apr_pstrcat(r->pool, result, name, NULL);
525       }
526     }
527     else
528     if ( (strncasecmp(name, "_chxj_c_", 8) == 0 || strncasecmp(name, "%5Fchxj%5Fc%5F", sizeof("%5Fchxj%5Fc%5F")-1) == 0)
529       || (strncasecmp(name, "_chxj_r_", 8) == 0 || strncasecmp(name, "%5Fchxj%5Fr%5F", sizeof("%5Fchxj%5Fr%5F")-1) == 0)
530       || (strncasecmp(name, "_chxj_s_", 8) == 0 || strncasecmp(name, "%5Fchxj%5Fs%5F", sizeof("%5Fchxj%5Fs%5F")-1) == 0)) {
531       if (value == NULL)
532         continue;
533
534       if (strlen(value) == 0)
535         continue;
536
537       if (strlen(result) != 0)
538         result = apr_pstrcat(r->pool, result, "&", NULL);
539
540       result = apr_pstrcat(r->pool, result, &name[8], "=", value, NULL);
541     }
542     else
543     if (strcasecmp(name, CHXJ_COOKIE_PARAM) == 0 || strcasecmp(name, "%5Fchxj%5Fcc") == 0) {
544       apr_table_unset(r->headers_in, "Cookie");
545       DBG(r, "found cookie parameter[%s]", value);
546       DBG(r, "call start chxj_load_cookie()");
547       cookie_lock_t *lock = chxj_cookie_lock(r);
548       cookie = chxj_load_cookie(r, value);
549       DBG(r, "call end   chxj_load_cookie()");
550       if (! no_update_flag && cookie) {
551         chxj_update_cookie(r, cookie);
552       }
553       chxj_cookie_unlock(r, lock);
554     }
555   }
556   r->args = result;
557
558   DBG(r, "result r->args=[%s]", r->args);
559   DBG(r, "end   chxj_convert_input_header()");
560   return 0;
561 }
562
563
564 /**
565  * It converts it from POSTDATA .
566  *
567  * @param r   [i]
568  * @param src [i]   It is POSTDATA character string.
569  * @param len [i/o] It is length of former HTML character string.
570  */
571 static char *
572 chxj_input_convert(
573   request_rec         *r, 
574   const char          **src, 
575   apr_size_t          *len, 
576   chxjconvrule_entry  *entryp)
577 {
578   char     *pair;
579   char     *name;
580   char     *value;
581   char     *pstate;
582   char     *vstate;
583   char     *s;
584   char     *result;
585   cookie_t *cookie;
586   char     *buff_pre;
587   int      no_update_flag = 0;
588
589   s        = apr_pstrdup(r->pool, *src);
590   buff_pre = apr_pstrdup(r->pool, *src);
591
592   result = qs_alloc_zero_byte_string(r->pool);
593
594   DBG(r, "BEFORE input convert source = [%s]", s);
595
596   for (;;) {
597     char *pair_sv;
598
599     pair = apr_strtok(buff_pre, "&", &pstate);
600     if (pair == NULL)
601       break;
602
603     buff_pre = NULL;
604
605     pair_sv = apr_pstrdup(r->pool, pair);
606
607     name  = apr_strtok(pair, "=", &vstate);
608     value = apr_strtok(NULL, "=", &vstate);
609     if (! name) continue;
610     if (strcasecmp(name, CHXJ_COOKIE_NOUPDATE_PARAM) == 0 || strcasecmp(name, chxj_url_encode(r->pool, CHXJ_COOKIE_NOUPDATE_PARAM)) == 0) {
611       DBG(r, "found cookie no update parameter");
612       no_update_flag++;
613     }
614   }
615
616   /* _chxj_dmy */
617   /* _chxj_c_ */
618   /* _chxj_r_ */
619   /* _chxj_s_ */
620   for (;;) {
621     pair = apr_strtok(s, "&", &pstate);
622     if (pair == NULL)
623       break;
624     s = NULL;
625
626     name  = apr_strtok(pair, "=", &vstate);
627     value = apr_strtok(NULL, "=", &vstate);
628     if (! name) continue;
629     if (strncasecmp(name, "_chxj", 5) != 0 && strncasecmp(name, "%5Fchxj", sizeof("%5Fchxj")-1) != 0) {
630       if (strlen(result) != 0) 
631         result = apr_pstrcat(r->pool, result, "&", NULL);
632
633       if (strcasecmp(entryp->encoding, "NONE") != 0) {
634         apr_size_t dlen;
635         char *dvalue;
636         char *dname;
637
638         if (value && *value != 0) {
639           value = chxj_url_decode(r->pool, value);
640           dlen   = strlen(value);
641           DBG(r, "************ before encoding[%s]", value);
642
643           dvalue = chxj_rencoding(r, value, &dlen);
644           dvalue = chxj_url_encode(r->pool, dvalue);
645
646           DBG(r, "************ after encoding[%s]", dvalue);
647         }
648         else {
649           dvalue = "";
650         }
651
652         if (name && *name != 0) {
653           name = chxj_url_decode(r->pool, name);
654           dlen = strlen(name);
655           dname = chxj_rencoding(r, name, &dlen);
656           dname = chxj_url_encode(r->pool, dname);
657         }
658         else {
659           dname = "";
660         }
661
662         result = apr_pstrcat(r->pool, result, dname, "=", dvalue, NULL);
663       }
664       else {
665         result = apr_pstrcat(r->pool, result, name, "=", value, NULL);
666       }
667     }
668     else
669     if ( (strncasecmp(name, "_chxj_c_", 8) == 0 || strncasecmp(name, "%5Fchxj%5Fc%5F", sizeof("%5Fchxj%5Fc%5F")-1) == 0)
670       || (strncasecmp(name, "_chxj_r_", 8) == 0 || strncasecmp(name, "%5Fchxj%5Fr%5F", sizeof("%5Fchxj%5Fr%5F")-1) == 0)
671       || (strncasecmp(name, "_chxj_s_", 8) == 0 || strncasecmp(name, "%5Fchxj%5Fs%5F", sizeof("%5Fchxj%5Fs%5F")-1) == 0)) {
672       if (value == NULL)
673         continue;
674
675       if (strlen(value) == 0)
676         continue;
677
678       if (strlen(result) != 0)
679         result = apr_pstrcat(r->pool, result, "&", NULL);
680
681       if (strcasecmp(entryp->encoding, "NONE") != 0 && value && strlen(value)) {
682         apr_size_t dlen;
683         char       *dvalue;
684
685         dlen   = strlen(value);
686         value = chxj_url_decode(r->pool, value);
687         DBG(r, "************ before encoding[%s]", value);
688
689         dvalue = chxj_rencoding(r, value, &dlen);
690         dvalue = chxj_url_encode(r->pool,dvalue);
691
692         DBG(r, "************ after encoding[%s]", dvalue);
693
694         result = apr_pstrcat(r->pool, result, &name[8], "=", dvalue, NULL);
695
696       }
697       else {
698         result = apr_pstrcat(r->pool, result, &name[8], "=", value, NULL);
699       }
700     }
701     else
702     if (strcasecmp(name, CHXJ_COOKIE_PARAM) == 0 || strcasecmp(name, "%5Fchxj%5Fcc") == 0) {
703       apr_table_unset(r->headers_in, "Cookie");
704       DBG(r, "found cookie parameter[%s]", value);
705       DBG(r, "call start chxj_load_cookie()");
706       cookie = chxj_load_cookie(r, value);
707       DBG(r, "call end   chxj_load_cookie()");
708       if (! no_update_flag && cookie) {
709         chxj_update_cookie(r, cookie);
710       }
711     }
712   }
713   *len = strlen(result);
714
715   DBG(r, "AFTER input convert result = [%s]", result);
716
717   return result;
718 }
719
720
721 /**
722  * The received data is returned to the filter.
723  *
724  * @param f    [i/o] It is a filter. 
725  * @param data [i]   It is data returned to the filter. 
726  * @param len  [i]   It is length of the data returned to the filter. 
727  */
728 static apr_status_t 
729 pass_data_to_filter(ap_filter_t *f, const char *data, 
730                                         apr_size_t len)
731 {
732   request_rec         *r = f->r;
733   conn_rec            *c = r->connection;
734   apr_status_t        rv;
735   apr_bucket_brigade  *bb;
736   apr_bucket          *b;
737
738   DBG(r, "start pass_data_to_filter()");
739
740   bb = apr_brigade_create(r->pool, c->bucket_alloc);
741   b  = apr_bucket_transient_create(data, len, c->bucket_alloc);
742
743   APR_BRIGADE_INSERT_TAIL(bb, b);
744   b = apr_bucket_eos_create(f->c->bucket_alloc);
745   APR_BRIGADE_INSERT_TAIL(bb, b);
746
747   rv = ap_pass_brigade(f->next, bb);
748   if (rv != APR_SUCCESS) {
749     DBG(r, "ap_pass_brigade()");
750     return rv;
751   }
752
753   DBG(r, "end pass_data_to_filter()");
754
755   return rv;
756 }
757
758
759 /**
760  * It is the main loop of the output filter. 
761  *
762  * @param f   [i/o] It is a filter.
763  * @param bb  [i]   
764  */
765 static apr_status_t 
766 chxj_output_filter(ap_filter_t *f, apr_bucket_brigade *bb)
767 {
768   request_rec         *r;
769   apr_status_t        rv;
770   apr_bucket          *b;
771   const char          *data;
772   char                *user_agent = NULL;
773   apr_size_t          len;
774   mod_chxj_ctx        *ctx = (mod_chxj_ctx *)f->ctx;
775   cookie_t            *cookie = NULL;
776   mod_chxj_config     *dconf;
777   chxjconvrule_entry  *entryp = NULL;
778   device_table        *spec = NULL;
779   apr_pool_t          *pool;
780
781   DBG(f->r, "start of chxj_output_filter()");
782   r  = f->r;
783   rv = APR_SUCCESS;
784
785   apr_pool_create(&pool, r->pool);
786
787   entryp = ctx->entryp;
788   spec   = ctx->spec;
789   dconf  = chxj_get_module_config(r->per_dir_config, &chxj_module);
790
791   if (r->content_type) {
792     if (! STRNCASEEQ('t','T',"text/html",r->content_type, sizeof("text/html")-1)
793     &&  ! STRNCASEEQ('t','T',"text/xml", r->content_type, sizeof("text/xml")-1)
794     &&  ! STRNCASEEQ('a','A',"application/xhtml+xml", r->content_type, sizeof("application/xhtml+xml")-1)
795     &&  ! (dconf->image == CHXJ_IMG_ON
796           && ! apr_table_get(r->headers_in, "CHXJ_IMG_CONV")
797           && STRNCASEEQ('i','I',"image/",  r->content_type, sizeof("image/") -1)
798           && ( STRCASEEQ('j','J',"jpeg",            &r->content_type[6])         /* JPEG */
799             || STRCASEEQ('j','J',"jp2",             &r->content_type[6])         /* JPEG2000 */
800             || STRCASEEQ('j','J',"jpeg2000",        &r->content_type[6])         /* JPEG2000 */
801             || STRCASEEQ('j','J',"jpeg2000-image",  &r->content_type[6])         /* JPEG2000 */
802             || STRCASEEQ('x','X',"x-jpeg2000-image",&r->content_type[6])         /* JPEG2000 */
803             || STRCASEEQ('p','P',"png",             &r->content_type[6])         /* PNG */
804             || STRCASEEQ('x','X',"x-png",           &r->content_type[6])         /* PNG */
805             || STRCASEEQ('g','G',"gif",             &r->content_type[6])))) {     /* GIF */
806       
807       DBG(r, "not convert content-type:[%s] dconf->image:[%d]", r->content_type, dconf->image);
808       if (entryp->action & CONVRULE_COOKIE_ON_BIT) {
809         cookie_lock_t *lock = NULL;
810         DBG(r, "entryp->action == COOKIE_ON_BIT");
811         switch(spec->html_spec_type) {
812         case CHXJ_SPEC_Chtml_1_0:
813         case CHXJ_SPEC_Chtml_2_0:
814         case CHXJ_SPEC_Chtml_3_0:
815         case CHXJ_SPEC_Chtml_4_0:
816         case CHXJ_SPEC_Chtml_5_0:
817         case CHXJ_SPEC_Chtml_6_0:
818         case CHXJ_SPEC_Chtml_7_0:
819         case CHXJ_SPEC_XHtml_Mobile_1_0:
820         case CHXJ_SPEC_Jhtml:
821           lock = chxj_cookie_lock(r);
822           cookie = chxj_save_cookie(r);
823           s_add_cookie_id_if_has_location_header(r, cookie);
824           chxj_cookie_unlock(r, lock);
825           break;
826         default:
827           break;
828         }
829       }
830       if (apr_table_get(r->headers_out, "Location") || apr_table_get(r->err_headers_out, "Location")) {
831         if (r->status < HTTP_MULTIPLE_CHOICES || r->status > HTTP_TEMPORARY_REDIRECT) {
832           r->status = HTTP_MOVED_TEMPORARILY;
833         }
834       }
835       ap_pass_brigade(f->next, bb);
836       return APR_SUCCESS;
837     }
838   }
839   else {
840     DBG(r, "not convert content-type:[(null)]");
841     ap_pass_brigade(f->next, bb);
842     return APR_SUCCESS;
843   }
844
845
846   for (b = APR_BRIGADE_FIRST(bb);
847        b != APR_BRIGADE_SENTINEL(bb); 
848        b = APR_BUCKET_NEXT(b)) {
849
850     if (apr_bucket_read(b, &data, &len, APR_BLOCK_READ) == APR_SUCCESS) {
851       DBG(r, "read data[%.*s]",(int)len, data);
852
853       /*--------------------------------------------------------------------*/
854       /* append data                                                        */
855       /*--------------------------------------------------------------------*/
856       char *tmp;
857       DBG(r, "append data start");
858       ctx = (mod_chxj_ctx *)f->ctx;
859
860       if (len > 0) {
861         tmp = apr_palloc(r->pool, ctx->len);
862         memcpy(tmp, ctx->buffer, ctx->len);
863
864         ctx->buffer = apr_palloc(pool, ctx->len + len);
865
866         memcpy(ctx->buffer, tmp, ctx->len);
867         memcpy(&ctx->buffer[ctx->len], data, len);
868
869         ctx->len += len;
870       }
871       DBG(r, "append data end");
872     }
873
874     if (APR_BUCKET_IS_EOS(b)) {
875
876       DBG(r, "eos");
877       /*----------------------------------------------------------------------*/
878       /* End Of File                                                          */
879       /*----------------------------------------------------------------------*/
880       if (ctx) {
881         cookie_lock_t *lock = NULL;
882         ctx = (mod_chxj_ctx *)f->ctx;
883
884         DBG(r, "content_type=[%s]", r->content_type);
885         lock = chxj_cookie_lock(r);
886
887         if (spec->html_spec_type != CHXJ_SPEC_UNKNOWN 
888             && r->content_type 
889             && (STRNCASEEQ('a','A',"application/xhtml+xml", r->content_type, sizeof("application/xhtml+xml")-1)
890             ||  STRNCASEEQ('t','T',"text/html", r->content_type, sizeof("text/html")-1))) {
891           DBG(r, "detect convert target:[%s]", r->content_type);
892
893           if (ctx->len) {
894             char *tmp;
895
896             tmp = apr_palloc(pool, ctx->len + 1);
897
898             memset(tmp, 0, ctx->len + 1);
899             memcpy(tmp, ctx->buffer, ctx->len);
900
901             ctx->buffer = chxj_convert(r, 
902                                        (const char **)&tmp, 
903                                        (apr_size_t *)&ctx->len,
904                                        spec,
905                                        user_agent, &cookie);
906
907           }
908           else {
909             ctx->buffer = apr_psprintf(r->pool, "\n");
910             ctx->len += 1;
911             ctx->buffer = chxj_convert(r, 
912                                        (const char **)&ctx->buffer, 
913                                        (apr_size_t *)&ctx->len,
914                                        spec,
915                                        user_agent, &cookie);
916
917           }
918         }
919         if (r->content_type
920             && *(char *)r->content_type == 't'
921             && strncmp(r->content_type, "text/xml",   8) == 0) {
922           DBG(r, "text/XML");
923
924           Doc       doc;
925           Node      *root;
926           Node      *child;
927           qr_code_t qrcode;
928           int       sts;
929       
930           memset(&doc,    0, sizeof(Doc));
931           memset(&qrcode, 0, sizeof(qr_code_t));
932           doc.r = r;
933           doc.parse_mode  = PARSE_MODE_CHTML;
934           qrcode.doc      = &doc;
935           qrcode.r        = r;
936       
937           qs_init_malloc(&doc);
938       
939           root = qs_parse_string(&doc, ctx->buffer, ctx->len);
940
941           sts = 0;
942           for (child = qs_get_child_node(&doc,root);
943                child ;
944                child = qs_get_next_node(&doc,child)) {
945             char *name = qs_get_node_name(&doc,child);
946             if (strcasecmp("qrcode",name) == 0) {
947               sts++;
948               break;
949             }
950           }
951           qs_all_free(&doc,QX_LOGMARK);
952           if (sts) {
953             r->handler = apr_psprintf(r->pool, "chxj-qrcode");
954             chxj_qrcode_node_to_qrcode(&qrcode, root);
955             sts = chxj_qrcode_create_image_data(&qrcode, &ctx->buffer, &ctx->len);
956             if (sts != OK) {
957               ERR(r, "qrcode create failed.");
958               chxj_cookie_unlock(r, lock);
959               return sts;
960             }
961             r->content_type = apr_psprintf(r->pool, "image/jpeg");
962           }
963         }
964
965         if (spec->html_spec_type != CHXJ_SPEC_UNKNOWN 
966             && r->content_type 
967             && ( *r->content_type == 'i' || *r->content_type == 'I')
968             && dconf->image == CHXJ_IMG_ON
969             && strncasecmp("image/", r->content_type, 6) == 0
970             && ( STRCASEEQ('j','J',"jpeg",            &r->content_type[6])         /* JPEG */
971               || STRCASEEQ('j','J',"jp2",             &r->content_type[6])         /* JPEG2000 */
972               || STRCASEEQ('j','J',"jpeg2000",        &r->content_type[6])         /* JPEG2000 */
973               || STRCASEEQ('j','J',"jpeg2000-image",  &r->content_type[6])         /* JPEG2000 */
974               || STRCASEEQ('x','X',"x-jpeg2000-image",&r->content_type[6])         /* JPEG2000 */
975               || STRCASEEQ('p','P',"png",             &r->content_type[6])         /* PNG */
976               || STRCASEEQ('x','X',"x-png",           &r->content_type[6])         /* PNG */
977               || STRCASEEQ('g','G',"gif",             &r->content_type[6]))) {     /* GIF */
978           if (ctx->len) {
979             char *tmp;
980
981             tmp = apr_palloc(pool, ctx->len + 1);
982
983             memset(tmp, 0, ctx->len + 1);
984             memcpy(tmp, ctx->buffer, ctx->len);
985             ctx->buffer = 
986               chxj_convert_image(r, 
987                                   (const char **)&tmp,
988                                   (apr_size_t *)&ctx->len);
989             if (ctx->buffer == NULL) {
990               ctx->buffer = tmp;
991             }
992           }
993         }
994
995         apr_table_unset(r->headers_out, "Content-Length");
996         apr_table_unset(r->err_headers_out, "Content-Length");
997         ap_set_content_length(r, (apr_off_t)ctx->len);
998
999         if (apr_table_get(r->headers_out, "Location") || apr_table_get(r->err_headers_out, "Location")) {
1000           if (r->status < HTTP_MULTIPLE_CHOICES || r->status > HTTP_TEMPORARY_REDIRECT) {
1001             r->status = HTTP_MOVED_TEMPORARILY;
1002           }
1003         }
1004         
1005         if (ctx->len > 0) {
1006           DBG(r, "call pass_data_to_filter()");
1007           s_add_cookie_id_if_has_location_header(r, cookie);
1008           chxj_cookie_unlock(r,lock);
1009           rv = pass_data_to_filter(f, 
1010                                    (const char *)ctx->buffer, 
1011                                    (apr_size_t)ctx->len);
1012         }
1013         else {
1014           chxj_cookie_unlock(r, lock);
1015
1016         }
1017         return rv;
1018       }
1019       else {
1020         DBG(r, " SAVE COOKIE[%x]", entryp->action);
1021
1022         /*
1023          * save cookie.
1024          */
1025         if (entryp->action & CONVRULE_COOKIE_ON_BIT) {
1026           cookie_lock_t *lock = NULL;
1027           DBG(r, "entryp->action == COOKIE_ON_BIT");
1028           switch(spec->html_spec_type) {
1029           case CHXJ_SPEC_Chtml_1_0:
1030           case CHXJ_SPEC_Chtml_2_0:
1031           case CHXJ_SPEC_Chtml_3_0:
1032           case CHXJ_SPEC_Chtml_4_0:
1033           case CHXJ_SPEC_Chtml_5_0:
1034           case CHXJ_SPEC_Chtml_6_0:
1035           case CHXJ_SPEC_Chtml_7_0:
1036           case CHXJ_SPEC_XHtml_Mobile_1_0:
1037           case CHXJ_SPEC_Jhtml:
1038             lock = chxj_cookie_lock(r);
1039             cookie = chxj_save_cookie(r);
1040             /*
1041              * Location Header Check to add cookie parameter.
1042              */
1043             s_add_cookie_id_if_has_location_header(r, cookie);
1044             chxj_cookie_unlock(r, lock);
1045             apr_table_unset(r->headers_out, "Set-Cookie");
1046             apr_table_unset(r->err_headers_out, "Set-Cookie");
1047             break;
1048
1049           default:
1050             break;
1051           }
1052         }
1053         if (apr_table_get(r->headers_out, "Location") || apr_table_get(r->err_headers_out, "Location")) {
1054           if (r->status < HTTP_MULTIPLE_CHOICES || r->status > HTTP_TEMPORARY_REDIRECT) {
1055             r->status = HTTP_MOVED_TEMPORARILY;
1056           }
1057         }
1058         apr_table_setn(r->headers_out, "Content-Length", "0");
1059         DBG(r, "call pass_data_to_filter()");
1060         rv = pass_data_to_filter(f, (const char *)"", (apr_size_t)0);
1061         return rv;
1062       }
1063     }
1064   }
1065   apr_brigade_destroy(bb);
1066
1067   DBG(r, "end of output filter");
1068
1069   return APR_SUCCESS;
1070 }
1071
1072 /**
1073  * Add Cookie_id if it has location header.
1074  */
1075 static void
1076 s_add_cookie_id_if_has_location_header(request_rec *r, cookie_t *cookie)
1077 {
1078   char *location_header = (char *)apr_table_get(r->headers_out, "Location");
1079   if (! location_header) {
1080     location_header = (char *)apr_table_get(r->err_headers_out, "Location");
1081   }
1082   if (cookie && location_header) {
1083     DBG(r, "Location Header=[%s]", location_header);
1084     location_header = chxj_add_cookie_parameter(r,
1085                                                 location_header,
1086                                                 cookie);
1087     apr_table_unset(r->headers_out, "Location");
1088     apr_table_setn(r->headers_out, "Location", location_header);
1089     DBG(r, "Location Header=[%s]", location_header);
1090     if (r->status < HTTP_MULTIPLE_CHOICES || r->status > HTTP_TEMPORARY_REDIRECT) {
1091       r->status = HTTP_MOVED_TEMPORARILY;
1092     }
1093   }
1094 }
1095
1096 /**
1097  * It is the main loop of the input filter handler. 
1098  *
1099  */
1100 static int 
1101 chxj_input_handler(request_rec *r)
1102 {
1103   mod_chxj_config     *dconf;
1104   chxjconvrule_entry  *entryp = NULL;
1105   device_table        *spec   = NULL;
1106   char                *post_data = NULL;
1107   apr_size_t          post_data_len = 0;
1108   char                *response;
1109   char                *user_agent;
1110   apr_pool_t          *pool;
1111   
1112   DBG(r, "start of chxj_input_handler()");
1113
1114   if (strcasecmp(r->handler, "chxj-input-handler")) {
1115     DBG(r, "end chxj_input_handler()");
1116     return DECLINED;
1117   }
1118   apr_pool_create(&pool, r->pool);
1119
1120   dconf      = chxj_get_module_config(r->per_dir_config, &chxj_module);
1121   user_agent = (char*)apr_table_get(r->headers_in, "User-Agent");
1122   spec       = chxj_specified_device(r, user_agent);
1123   entryp     = chxj_apply_convrule(r, dconf->convrules);
1124
1125   post_data = apr_pstrdup(pool, "");
1126   if (ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK) == OK) {
1127     if (ap_should_client_block(r)) {
1128       while (post_data_len < CHXJ_POST_MAX) {
1129 #define BUFSZ (256)
1130         char buffer[BUFSZ];
1131         int read_bytes = ap_get_client_block(r, buffer, BUFSZ-1);
1132         if (read_bytes<=0) {
1133           break;
1134         }
1135         buffer[read_bytes] = '\0';
1136         post_data = apr_pstrcat(pool, post_data, buffer, NULL);
1137         post_data_len += read_bytes;
1138 #undef BUFSZ
1139       }
1140     }
1141   }
1142
1143   /* 
1144    * now convert.
1145    */
1146   if (post_data_len > 0) {
1147     post_data = chxj_input_convert(r, (const char**)&post_data, (apr_size_t*)&post_data_len, entryp);
1148     DBG(r, "(in:exchange)POSTDATA:[%s]", post_data);
1149   }
1150
1151   char *url_path;
1152   if (dconf->forward_url_base) {
1153     url_path = apr_psprintf(pool, "%s%s", dconf->forward_url_base, r->uri);
1154   }
1155   else {
1156     url_path = apr_psprintf(pool, "%s://%s:%d%s", chxj_apache_run_http_scheme(r), ap_get_server_name(r), ap_get_server_port(r), r->uri);
1157   }
1158   if (r->args) {
1159     url_path = apr_pstrcat(pool, url_path, "?", r->args, NULL);
1160   }
1161   DBG(r, "==> new url_path:[%s]", url_path);
1162
1163   apr_size_t res_len;
1164   apr_table_setn(r->headers_in, CHXJ_HEADER_ORIG_CLIENT_IP, r->connection->remote_ip);
1165   apr_table_unset(r->headers_in, "Content-Length");
1166   apr_table_setn(r->headers_in, "Content-Length", apr_psprintf(pool, "%" APR_SIZE_T_FMT, post_data_len));
1167   response = chxj_serf_post(r, pool, url_path, post_data, post_data_len, 1, &res_len);
1168   DBG(r, "REQ[%X] response:[%.*s][%" APR_SIZE_T_FMT  "]", (unsigned int)(apr_size_t)r, (unsigned int)res_len, response, res_len);
1169
1170   char *chunked;
1171   if ((chunked = (char *)apr_table_get(r->headers_out, "Transfer-Encoding")) != NULL) {
1172     if (strcasecmp(chunked, "chunked") == 0) {
1173       r->chunked = 1;  
1174       apr_table_unset(r->headers_out, "Transfer-Encoding");
1175     }
1176   }
1177   {
1178     apr_pool_t *wpool;
1179     apr_pool_create(&wpool, r->pool);
1180     apr_bucket_brigade *bb;
1181     apr_bucket *e;
1182     apr_status_t rv;
1183     conn_rec *c = r->connection;
1184     
1185     bb = apr_brigade_create(wpool, c->bucket_alloc);
1186     e = apr_bucket_heap_create(response, res_len, NULL, c->bucket_alloc);
1187     APR_BRIGADE_INSERT_TAIL(bb, e);
1188     e = apr_bucket_eos_create(c->bucket_alloc);
1189     APR_BRIGADE_INSERT_TAIL(bb, e);
1190     if ((rv = ap_pass_brigade(r->output_filters, bb)) != APR_SUCCESS) {
1191       ERR(r, "%s:%d failed ap_pass_brigade()", APLOG_MARK);
1192       return rv;
1193     }
1194     apr_brigade_cleanup(bb);
1195   }  
1196
1197   DBG(r, "end of chxj_input_handler()");
1198   return APR_SUCCESS;
1199 }
1200
1201 static mod_chxj_global_config *
1202 chxj_global_config_create(apr_pool_t *pool, server_rec *s)
1203 {
1204   mod_chxj_global_config *conf;
1205
1206   SDBG(s, "start chxj_global_config_create()");
1207
1208   /*--------------------------------------------------------------------------*/
1209   /* allocate an own subpool which survives server restarts                   */
1210   /*--------------------------------------------------------------------------*/
1211   conf = (mod_chxj_global_config *)apr_palloc(pool, 
1212                   sizeof(mod_chxj_global_config));
1213 #if 0
1214   conf->cookie_db_lock = NULL;
1215 #endif
1216   SDBG(s, "end   chxj_global_config_create()");
1217
1218   return conf;
1219 }
1220
1221
1222 /**
1223  * initialize chxj module
1224  */
1225 static int 
1226 chxj_init_module(apr_pool_t *p, 
1227                  apr_pool_t *UNUSED(plog), 
1228                  apr_pool_t *UNUSED(ptemp), 
1229                  server_rec *s)
1230 {
1231   void *user_data;
1232   apr_status_t rv;
1233
1234   SDBG(s, "start chxj_init_module()");
1235
1236   apr_pool_userdata_get(&user_data, CHXJ_MOD_CONFIG_KEY, s->process->pool);
1237   SDBG(s, " ");
1238   if (user_data == NULL) {
1239     SDBG(s, " ");
1240     /*
1241      * dummy user_data set.
1242      */
1243     apr_pool_userdata_set(
1244       (const void *)(1), 
1245       CHXJ_MOD_CONFIG_KEY, 
1246       apr_pool_cleanup_null, 
1247       s->process->pool);
1248     SDBG(s, "end  chxj_init_module()");
1249     return OK;
1250   }
1251
1252   ap_add_version_component(p, CHXJ_VERSION_PREFIX CHXJ_VERSION);
1253
1254   if ((rv = apr_proc_mutex_create(&global_cookie_mutex, NULL,  APR_LOCK_FCNTL, s->process->pool)) != APR_SUCCESS) {
1255     char errstr[255];
1256     SERR(s, "%s:%d end chxj_init_module(). mutex create failure.(%d:%s)",APLOG_MARK, rv,apr_strerror(rv,errstr,255));
1257     return HTTP_INTERNAL_SERVER_ERROR;
1258   }
1259
1260   SDBG(s, "end  chxj_init_module()");
1261
1262   return OK;
1263 }
1264
1265
1266 static void 
1267 chxj_child_init(apr_pool_t *UNUSED(p), server_rec *s)
1268 {
1269   apr_status_t rv;
1270   SDBG(s, "start chxj_child_init()");
1271   if ((rv = apr_proc_mutex_child_init(&global_cookie_mutex, NULL, s->process->pool)) != APR_SUCCESS) {
1272     char errstr[255];
1273     SERR(s, "%s:%d ERROR end chxj_init_module(). mutex create failure.(%d:%s)", APLOG_MARK, rv,apr_strerror(rv,errstr,255));
1274   }
1275   SDBG(s, "end   chxj_child_init()");
1276 }
1277
1278
1279 /**
1280  * A set structure of each server is generated. 
1281  * 
1282  * @param p
1283  * @param s
1284  */
1285 static void *
1286 chxj_config_server_create(apr_pool_t *p, server_rec *s)
1287 {
1288   mod_chxj_global_config *gc;
1289
1290   gc = chxj_global_config_create(p,s);
1291
1292   return gc;
1293 }
1294
1295
1296 static int
1297 chxj_translate_name(request_rec *r)
1298 {
1299   return chxj_trans_name(r);
1300 }
1301
1302
1303 static void 
1304 chxj_insert_filter(request_rec *r)
1305 {
1306   char                *user_agent;
1307   device_table        *spec;
1308   mod_chxj_config     *dconf;
1309   chxjconvrule_entry  *entryp;
1310   mod_chxj_ctx        *ctx;
1311   apr_status_t        rv;
1312   char                *contentType;
1313
1314   DBG(r, "start chxj_insert_filter()");
1315
1316   dconf = chxj_get_module_config(r->per_dir_config, &chxj_module);
1317
1318   user_agent = (char*)apr_table_get(r->headers_in, HTTP_USER_AGENT);
1319
1320   contentType = (char *)apr_table_get(r->headers_in, "Content-Type");
1321   if (contentType
1322       && strncasecmp("multipart/form-data", contentType, 19) == 0) {
1323     DBG(r, "detect multipart/form-data ==> no target");
1324     return;
1325   }
1326
1327   spec = chxj_specified_device(r, user_agent);
1328   entryp = chxj_apply_convrule(r, dconf->convrules);
1329   if (!entryp) {
1330     DBG(r, "end chxj_insert_filter()");
1331     return;
1332   }
1333   ctx = apr_palloc(r->pool, sizeof(*ctx));
1334   memset(ctx, 0, sizeof(*ctx));
1335   if ((rv = apr_pool_create(&ctx->pool, r->pool)) != APR_SUCCESS) {
1336     ERR(r, "failed: new pool create. rv:[%d]", rv);
1337     return;
1338   }
1339   ctx->entryp = entryp;
1340   ctx->spec   = spec;
1341   ctx->buffer = apr_palloc(ctx->pool, 1);
1342   ctx->buffer[0] = 0;
1343
1344   if (!entryp || !(entryp->action & CONVRULE_ENGINE_ON_BIT)) {
1345     DBG(r,"EngineOff");
1346     return;
1347   }
1348
1349   switch(spec->html_spec_type) {
1350   case CHXJ_SPEC_Chtml_1_0:
1351   case CHXJ_SPEC_Chtml_2_0:
1352   case CHXJ_SPEC_Chtml_3_0:
1353   case CHXJ_SPEC_Chtml_4_0:
1354   case CHXJ_SPEC_Chtml_5_0:
1355   case CHXJ_SPEC_Chtml_6_0:
1356   case CHXJ_SPEC_Chtml_7_0:
1357   case CHXJ_SPEC_XHtml_Mobile_1_0:
1358   case CHXJ_SPEC_Hdml:
1359   case CHXJ_SPEC_Jhtml:
1360   case CHXJ_SPEC_Jxhtml:
1361     break;
1362
1363   default:
1364     return;
1365   }
1366
1367
1368   if (! apr_table_get(r->headers_in, "X-Chxj-Forward")) {
1369     ap_add_output_filter("chxj_output_filter", ctx, r, r->connection);
1370     DBG(r, "added Output Filter");
1371   }
1372
1373   DBG(r, "end   chxj_insert_filter()");
1374 }
1375
1376
1377 /**
1378  * The hook is registered.
1379  *
1380  * @param p
1381  */
1382 static void 
1383 chxj_register_hooks(apr_pool_t *UNUSED(p))
1384 {
1385   ap_hook_post_config(chxj_init_module,
1386                       NULL,
1387                       NULL,
1388                       APR_HOOK_REALLY_FIRST);
1389   ap_hook_child_init(chxj_child_init, 
1390                      NULL, 
1391                      NULL, 
1392                      APR_HOOK_REALLY_FIRST);
1393   ap_register_output_filter (
1394                       "chxj_output_filter", 
1395                       chxj_output_filter, 
1396                       NULL, 
1397                       AP_FTYPE_RESOURCE);
1398   ap_hook_insert_filter(chxj_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
1399   ap_hook_handler(chxj_img_conv_format_handler, NULL, NULL, APR_HOOK_MIDDLE);
1400   ap_hook_handler(chxj_qr_code_handler, NULL, NULL, APR_HOOK_MIDDLE);
1401   ap_hook_handler(chxj_input_handler, NULL, NULL, APR_HOOK_MIDDLE);
1402   ap_hook_translate_name(chxj_translate_name, NULL, NULL, APR_HOOK_MIDDLE);
1403   ap_hook_fixups(chxj_headers_fixup, NULL, NULL, APR_HOOK_FIRST);
1404 }
1405
1406
1407 /**
1408  * A set structure according to the directory is generated. 
1409  *
1410  * @param p
1411  * @param arg
1412  */
1413 static void * 
1414 chxj_create_per_dir_config(apr_pool_t *p, char *arg) 
1415 {
1416   mod_chxj_config *conf;
1417
1418   conf = apr_pcalloc(p, sizeof(mod_chxj_config));
1419   conf->device_data_file = NULL;
1420   conf->devices          = NULL;
1421   conf->emoji_data_file  = NULL;
1422   conf->emoji            = NULL;
1423   conf->emoji_tail       = NULL;
1424   conf->image            = CHXJ_IMG_NONE;
1425   conf->image_cache_dir  = apr_psprintf(p, "%s",DEFAULT_IMAGE_CACHE_DIR);
1426   conf->image_cache_limit = 0;
1427   conf->server_side_encoding = NULL;
1428   conf->cookie_db_dir    = NULL;
1429   conf->cookie_timeout   = 0;
1430   conf->cookie_store_type = COOKIE_STORE_TYPE_NONE;
1431   conf->cookie_lazy_mode  = 0;
1432 #if defined(USE_MYSQL_COOKIE)
1433   memset((void *)&conf->mysql, 0, sizeof(mysql_t));
1434   conf->mysql.port       = MYSQL_PORT;
1435   conf->mysql.host       = NULL;
1436 #endif
1437 #if defined(USE_MEMCACHE_COOKIE)
1438   memset((void *)&conf->memcache, 0, sizeof(memcache_t));
1439   conf->memcache.host    = NULL;
1440   conf->memcache.port    = 0;
1441 #endif
1442   conf->forward_url_base = NULL;
1443   conf->forward_server_ip = NULL;
1444
1445   if (arg == NULL) {
1446     conf->dir                  = NULL;
1447   }
1448   else {
1449     conf->dir                  = apr_pcalloc(p, strlen(arg)+1);
1450     memset(conf->dir, 0, strlen(arg)+1);
1451     strcpy(conf->dir, arg);
1452   }
1453   conf->convrules   = apr_array_make(p, 2, sizeof(chxjconvrule_entry));
1454
1455   /* Default is copyleft */
1456   conf->image_copyright = NULL; 
1457
1458   return conf;
1459 }
1460
1461
1462 /*
1463  *  Merge per-directory CHXJ configurations
1464  */
1465 static void *
1466 chxj_merge_per_dir_config(apr_pool_t *p, void *basev, void *addv)
1467 {
1468   mod_chxj_config *base;
1469   mod_chxj_config *add;
1470   mod_chxj_config *mrg;
1471
1472   base = (mod_chxj_config *)basev;
1473   add  = (mod_chxj_config *)addv;
1474   mrg  = (mod_chxj_config *)apr_palloc(p, sizeof(mod_chxj_config));
1475
1476   mrg->device_data_file = NULL;
1477   mrg->devices          = NULL;
1478   mrg->emoji_data_file  = NULL;
1479   mrg->image            = CHXJ_IMG_NONE;
1480   mrg->image_cache_dir  = NULL;
1481   mrg->image_copyright  = NULL;
1482   mrg->image_cache_limit  = 0;
1483   mrg->emoji            = NULL;
1484   mrg->emoji_tail       = NULL;
1485   mrg->new_line_type    = NLTYPE_NIL;
1486   mrg->forward_url_base = NULL;
1487   mrg->forward_server_ip = NULL;
1488
1489   mrg->dir = apr_pstrdup(p, add->dir);
1490
1491   if (! add->device_data_file) {
1492     mrg->devices = base->devices;
1493     mrg->device_data_file = apr_pstrdup(p, base->device_data_file);
1494   }
1495   else {
1496     mrg->devices = add->devices;
1497     mrg->device_data_file = apr_pstrdup(p, add->device_data_file);
1498   }
1499
1500   if (! add->emoji_data_file) {
1501     mrg->emoji = base->emoji;
1502     mrg->emoji_tail = base->emoji_tail;
1503     mrg->emoji_data_file = apr_pstrdup(p, base->emoji_data_file);
1504   }
1505   else {
1506     mrg->emoji = add->emoji;
1507     mrg->emoji_tail = add->emoji_tail;
1508     mrg->emoji_data_file = apr_pstrdup(p, add->emoji_data_file);
1509   }
1510
1511   if (add->image == CHXJ_IMG_NONE) {
1512     mrg->image = base->image;
1513   }
1514   else {
1515     mrg->image = add->image;
1516   }
1517
1518   if (strcasecmp(add->image_cache_dir ,DEFAULT_IMAGE_CACHE_DIR)==0) {
1519     mrg->image_cache_dir = apr_pstrdup(p, base->image_cache_dir);
1520   }
1521   else {
1522     mrg->image_cache_dir = apr_pstrdup(p, add->image_cache_dir);
1523   }
1524
1525   if (add->image_cache_limit) {
1526     mrg->image_cache_limit = add->image_cache_limit;
1527   }
1528   else {
1529     mrg->image_cache_limit = base->image_cache_limit;
1530   }
1531
1532   if (add->image_copyright) 
1533     mrg->image_copyright = apr_pstrdup(p, add->image_copyright);
1534   else
1535     mrg->image_copyright = apr_pstrdup(p, base->image_copyright);
1536
1537   if (add->server_side_encoding) {
1538     mrg->server_side_encoding = apr_pstrdup(p, add->server_side_encoding);
1539   }
1540   else 
1541   if (base->server_side_encoding) {
1542     mrg->server_side_encoding = apr_pstrdup(p, base->server_side_encoding);
1543   }
1544   else {
1545     mrg->server_side_encoding = apr_pstrdup(p, DEFAULT_SERVER_SIDE_ENCODING);
1546   }
1547
1548   mrg->convrules    = apr_array_append(p, add->convrules, base->convrules);
1549
1550   if (add->cookie_db_dir) {
1551     mrg->cookie_db_dir = apr_pstrdup(p, add->cookie_db_dir);
1552   }
1553   else
1554   if (base->cookie_db_dir) {
1555     mrg->cookie_db_dir = apr_pstrdup(p, base->cookie_db_dir);
1556   }
1557   else {
1558     mrg->cookie_db_dir = NULL;
1559   }
1560
1561   if (add->cookie_timeout) {
1562     mrg->cookie_timeout   = add->cookie_timeout;
1563   }
1564   else
1565   if (base->cookie_db_dir) {
1566     mrg->cookie_timeout   = base->cookie_timeout;
1567   }
1568   else {
1569     mrg->cookie_timeout   = 0;
1570   }
1571
1572 #if defined(USE_MYSQL_COOKIE)
1573   if (add->mysql.host) {
1574     mrg->mysql.host = apr_pstrdup(p, add->mysql.host);
1575   }
1576   else if (base->mysql.host) {
1577     mrg->mysql.host = apr_pstrdup(p, base->mysql.host);
1578   }
1579   else {
1580     mrg->mysql.host = NULL;
1581   }
1582   if (add->mysql.port) {
1583     mrg->mysql.port = add->mysql.port;
1584   }
1585   else if (base->mysql.port) {
1586     mrg->mysql.port = base->mysql.port;
1587   }
1588   else {
1589     mrg->mysql.port = 0;
1590   }
1591
1592   if (add->mysql.database) {
1593     mrg->mysql.database = apr_pstrdup(p, add->mysql.database);
1594   }
1595   else if (base->mysql.database) {
1596     mrg->mysql.database = apr_pstrdup(p, base->mysql.database);
1597   }
1598   else {
1599     mrg->mysql.database = NULL;
1600   }
1601
1602   if (add->mysql.username) {
1603     mrg->mysql.username = apr_pstrdup(p, add->mysql.username);
1604   }
1605   else if (base->mysql.username) {
1606     mrg->mysql.username = apr_pstrdup(p, base->mysql.username);
1607   }
1608   else {
1609     mrg->mysql.username = NULL;
1610   }
1611
1612   if (add->mysql.password) {
1613     mrg->mysql.password = apr_pstrdup(p, add->mysql.password);
1614   }
1615   else if (base->mysql.password) {
1616     mrg->mysql.password = apr_pstrdup(p, base->mysql.password);
1617   }
1618   else {
1619     mrg->mysql.password = NULL;
1620   }
1621
1622   if (add->mysql.tablename) {
1623     mrg->mysql.tablename = apr_pstrdup(p, add->mysql.tablename);
1624   }
1625   else if (base->mysql.tablename) {
1626     mrg->mysql.tablename = apr_pstrdup(p, base->mysql.tablename);
1627   }
1628   else {
1629     mrg->mysql.tablename = NULL;
1630   }
1631
1632   if (add->mysql.socket_path) {
1633     mrg->mysql.socket_path = apr_pstrdup(p, add->mysql.socket_path);
1634   }
1635   else if (base->mysql.socket_path) {
1636     mrg->mysql.socket_path = apr_pstrdup(p, base->mysql.socket_path);
1637   }
1638   else {
1639     mrg->mysql.socket_path = NULL;
1640   }
1641
1642   if (add->mysql.charset) {
1643     mrg->mysql.charset = apr_pstrdup(p, add->mysql.charset);
1644   }
1645   else if (base->mysql.charset) {
1646     mrg->mysql.charset = apr_pstrdup(p, base->mysql.charset);
1647   }
1648   else {
1649     mrg->mysql.charset = NULL;
1650   }
1651 #endif
1652 #if defined(USE_MEMCACHE_COOKIE)
1653   if (add->memcache.host) {
1654     mrg->memcache.host = apr_pstrdup(p, add->memcache.host);
1655   }
1656   else if (base->memcache.host) {
1657     mrg->memcache.host = apr_pstrdup(p, base->memcache.host);
1658   }
1659   else {
1660     mrg->memcache.host = NULL;
1661   }
1662   if (add->memcache.port) {
1663     mrg->memcache.port = add->memcache.port;
1664   }
1665   else if (base->memcache.port) {
1666     mrg->memcache.port = base->memcache.port;
1667   }
1668   else {
1669     mrg->memcache.port = 0;
1670   }
1671 #endif
1672   if (add->cookie_store_type) {
1673     mrg->cookie_store_type = add->cookie_store_type;
1674   }
1675   else if (base->cookie_store_type) {
1676     mrg->cookie_store_type = base->cookie_store_type;
1677   }
1678   else {
1679     mrg->cookie_store_type = COOKIE_STORE_TYPE_NONE;
1680   }
1681   if (add->cookie_lazy_mode) {
1682     mrg->cookie_lazy_mode = add->cookie_lazy_mode;
1683   }
1684   else if (base->cookie_lazy_mode) {
1685     mrg->cookie_lazy_mode = base->cookie_lazy_mode;
1686   }
1687   else {
1688     mrg->cookie_lazy_mode = 0;
1689   }
1690   if (add->new_line_type) {
1691     mrg->new_line_type = add->new_line_type;
1692   }
1693   else if (base->new_line_type) {
1694     mrg->new_line_type = base->new_line_type;
1695   }
1696   else {
1697     mrg->new_line_type = NLTYPE_NIL;
1698   }
1699   return mrg;
1700 }
1701
1702
1703 static int
1704 chxj_command_parse_take5(
1705   const char *arg, 
1706   char       **prm1, 
1707   char       **prm2, 
1708   char       **prm3, 
1709   char       **prm4, 
1710   char       **prm5)
1711 {
1712   int  isquoted;
1713   char *strp;
1714
1715   strp = (char *)arg;
1716
1717   for (;*strp == ' '||*strp == '\t'; strp++) ;
1718
1719   isquoted = 0; 
1720   if (*strp == '"') { 
1721     isquoted = 1;
1722     strp++;
1723   }
1724
1725   *prm1 = strp;
1726
1727   for (; *strp != '\0'; strp++) {
1728     if ((isquoted && (*strp == ' ' || *strp == '\t'))
1729     ||  (*strp == '\\' && (*(strp+1) == ' ' || *(strp+1) == '\t'))) {
1730       strp++;
1731       continue;
1732     }
1733
1734     if ((!isquoted && (*strp == ' ' || *strp == '\t'))
1735     ||  (isquoted  && *strp == '"'))
1736       break;
1737   }
1738
1739   if (! *strp) {
1740     *prm2 = strp;
1741     *prm3 = strp;
1742     *prm4 = strp;
1743     *prm5 = strp;
1744     return 1;
1745   }
1746
1747   *strp++ = '\0';
1748
1749   for (;*strp == ' '||*strp == '\t'; strp++) ;
1750
1751   isquoted = 0; 
1752   if (*strp == '"') { 
1753     isquoted = 1;
1754     strp++;
1755   }
1756
1757   *prm2 = strp;
1758   for (; *strp != '\0'; strp++) {
1759     if ((isquoted && (*strp == ' ' || *strp == '\t'))
1760     ||  (*strp == '\\' && (*(strp+1) == ' ' || *(strp+1) == '\t'))) {
1761       strp++;
1762       continue;
1763     }
1764
1765     if ((!isquoted && (*strp == ' ' || *strp == '\t'))
1766     ||  (isquoted  && *strp == '"'))
1767       break;
1768   }
1769
1770   if (! *strp) {
1771     *prm3 = strp;
1772     *prm4 = strp;
1773     *prm5 = strp;
1774     return 0;
1775   }
1776
1777   *strp++ = '\0';
1778
1779   for (;*strp == ' '||*strp == '\t'; strp++);
1780
1781   isquoted = 0; 
1782   if (*strp == '"') { 
1783     isquoted = 1;
1784     strp++;
1785   }
1786   *prm3 = strp;
1787   for (; *strp != '\0'; strp++) {
1788     if ((isquoted && (*strp == ' ' || *strp == '\t'))
1789     ||  (*strp == '\\' && (*(strp+1) == ' ' || *(strp+1) == '\t'))) {
1790       strp++;
1791       continue;
1792     }
1793
1794     if ((!isquoted && (*strp == ' ' || *strp == '\t'))
1795     ||  (isquoted  && *strp == '"'))
1796       break;
1797   }
1798
1799   if (! *strp) {
1800     *prm4 = strp;
1801     *prm5 = strp;
1802     return 0;
1803   }
1804
1805   *strp++ = '\0';
1806
1807   for (;*strp == ' '||*strp == '\t'; strp++);
1808
1809   isquoted = 0; 
1810   if (*strp == '"') { 
1811     isquoted = 1;
1812     strp++;
1813   }
1814   *prm4 = strp;
1815   for (; *strp != '\0'; strp++) {
1816     if ((isquoted && (*strp == ' ' || *strp == '\t'))
1817     ||  (*strp == '\\' && (*(strp+1) == ' ' || *(strp+1) == '\t'))) {
1818       strp++;
1819       continue;
1820     }
1821
1822     if ((!isquoted && (*strp == ' ' || *strp == '\t'))
1823     ||  (isquoted  && *strp == '"'))
1824       break;
1825   }
1826
1827   if (! *strp) {
1828     *prm5 = strp;
1829     return 0;
1830   }
1831
1832   *strp++ = '\0';
1833
1834   for (;*strp == ' '||*strp == '\t'; strp++);
1835
1836   isquoted = 0; 
1837   if (*strp == '"') { 
1838     isquoted = 1;
1839     strp++;
1840   }
1841   *prm5 = strp;
1842   for (; *strp != '\0'; strp++) {
1843     if ((isquoted && (*strp == ' ' || *strp == '\t'))
1844     ||  (*strp == '\\' && (*(strp+1) == ' ' || *(strp+1) == '\t'))) {
1845       strp++;
1846       continue;
1847     }
1848
1849     if ((!isquoted && (*strp == ' ' || *strp == '\t'))
1850     ||  (isquoted  && *strp == '"'))
1851       break;
1852   }
1853   *strp = '\0';
1854
1855   return 0;
1856 }
1857
1858
1859 /**
1860  * The device definition file is loaded. 
1861  *
1862  * @param arg     [i]   The name of the device definition file is specified.
1863  * @param mconfig [i/o] The pointer to a set structure is specified. 
1864  * @param parms   [i]   
1865  */
1866 static const char * 
1867 cmd_load_device_data(cmd_parms *parms, void *mconfig, const char *arg) 
1868 {
1869   mod_chxj_config  *conf;
1870   Doc              doc;
1871
1872   doc.r = NULL;
1873
1874   if (strlen(arg) > 256) 
1875     return "mod_chxj: device data filename too long.";
1876
1877   conf = (mod_chxj_config *)mconfig;
1878   conf->device_data_file = apr_pstrdup(parms->pool, arg);
1879
1880   qs_init_malloc(&doc);
1881   qs_init_root_node(&doc);
1882
1883   qs_parse_file((Doc *)&doc, (const char *)arg);
1884   chxj_load_device_data(&doc,parms->pool, conf);
1885   qs_all_free(&doc, QX_LOGMARK);
1886
1887   return NULL;
1888 }
1889
1890
1891 /**
1892  * Device definition information is loaded. 
1893  *
1894  * @param parms 
1895  * @param arg     [i]   The name of the device definition file is specified. 
1896  * @param mconfig [i/o] The pointer to a set structure is specified. 
1897  * @return 
1898  */
1899 static const char * 
1900 cmd_load_emoji_data(cmd_parms *parms, void *mconfig, const char *arg) 
1901 {
1902   mod_chxj_config *conf;
1903   char            *rtn;
1904   Doc              doc;
1905
1906   doc.r = NULL;
1907
1908
1909   if (strlen(arg) > 256) 
1910     return "mod_chxj: emoji data filename too long.";
1911
1912   conf = (mod_chxj_config *)mconfig;
1913   conf->emoji_data_file = apr_pstrdup(parms->pool, arg);
1914   qs_init_malloc(&doc);
1915   qs_init_root_node(&doc);
1916
1917   qs_parse_file((Doc *)&doc, (const char *)arg);
1918
1919   rtn = chxj_load_emoji_data(&doc,parms->pool, conf);
1920
1921   qs_all_free(&doc, QX_LOGMARK);
1922
1923
1924   return rtn;
1925 }
1926
1927
1928 static const char * 
1929 cmd_set_image_engine(cmd_parms * UNUSED(parms), void *mconfig, const char *arg) 
1930 {
1931   mod_chxj_config *conf;
1932   Doc              doc;
1933
1934   doc.r = NULL;
1935
1936   if (strlen(arg) > 256) 
1937     return "image uri is too long.";
1938
1939   conf = (mod_chxj_config*)mconfig;
1940   if (strcasecmp("ON", arg) == 0) {
1941     conf->image = CHXJ_IMG_ON;
1942   }
1943   else {
1944     conf->image = CHXJ_IMG_OFF;
1945   }
1946
1947   return NULL;
1948 }
1949
1950
1951 static const char * 
1952 cmd_set_image_cache_dir(cmd_parms *parms, void *mconfig, const char *arg) 
1953 {
1954   mod_chxj_config *conf;
1955   Doc              doc;
1956
1957   doc.r = NULL;
1958
1959   if (strlen(arg) > 256) 
1960     return "cache dir name is too long.";
1961
1962   conf = (mod_chxj_config *)mconfig;
1963   conf->image_cache_dir = apr_pstrdup(parms->pool, arg);
1964
1965   return NULL;
1966 }
1967
1968
1969 static const char * 
1970 cmd_set_image_cache_limit(cmd_parms *parms, void *mconfig, const char *arg) 
1971 {
1972   mod_chxj_config *conf;
1973   Doc              doc;
1974
1975   doc.r = NULL;
1976
1977   if (strlen(arg) > IMAGE_CACHE_LIMIT_FMT_LEN) 
1978     return "cache size is too long.";
1979
1980   conf = (mod_chxj_config *)mconfig;
1981   errno = 0;
1982   /* 
1983    * I use strtol function because strtoul is not portable function. 
1984    */
1985   conf->image_cache_limit = (unsigned long)strtol(arg, NULL, 10);
1986   switch (errno) {
1987   case EINVAL:
1988     return apr_psprintf(parms->pool, "ChxjImageCacheLimit invalid value [%s] errno:[%d]", arg, errno);
1989   case ERANGE:
1990     return apr_psprintf(parms->pool, "ChxjImageCacheLimit Out of range [%s] errno:[%d]", arg, errno);
1991   default:
1992     break;
1993   }
1994   return NULL;
1995 }
1996
1997
1998 static const char * 
1999 cmd_set_image_copyright(cmd_parms *parms, void *mconfig, const char *arg) 
2000 {
2001   mod_chxj_config *conf;
2002   Doc              doc;
2003
2004   doc.r = NULL;
2005
2006   if (strlen(arg) > 256) 
2007     return "Copyright Flag is too long.";
2008
2009   conf = (mod_chxj_config *)mconfig;
2010   conf->image_copyright = apr_pstrdup(parms->pool, arg);
2011
2012   return NULL;
2013 }
2014
2015
2016 static const char *
2017 cmd_convert_rule(cmd_parms *cmd, void *mconfig, const char *arg)
2018 {
2019   int                 mode;
2020   ap_regex_t          *regexp;
2021   mod_chxj_config     *dconf;
2022   chxjconvrule_entry  *newrule;
2023   char                *prm1;
2024   char                *prm2;
2025   char                *prm3;
2026   char                *prm4;
2027   char                *prm5;
2028   char                *pstate;
2029   char                *action;
2030   char                *pp;
2031
2032   dconf = (mod_chxj_config *)mconfig;
2033
2034   if (strlen(arg) > 4096) 
2035     return "mod_chxj: ChxjConvertRule: is too long.";
2036
2037   dconf = (mod_chxj_config *)mconfig;
2038   if (dconf->convrules == NULL)
2039     dconf->convrules   = apr_array_make(cmd->pool, 
2040                                         2, 
2041                                         sizeof(chxjconvrule_entry));
2042
2043   newrule = apr_array_push(dconf->convrules);
2044
2045   newrule->flags  = 0;
2046   newrule->action = 0;
2047
2048   if (chxj_command_parse_take5(arg, &prm1, &prm2, &prm3, &prm4, &prm5))
2049     return "ChxjConvertRule: bad argument line";
2050
2051   newrule->pattern = apr_pstrdup(cmd->pool, prm1);
2052
2053   /* Parse action */
2054   for (;;) {
2055     if ((action = apr_strtok(prm2, ",", &pstate)) == NULL)
2056       break;
2057     prm2 = NULL;
2058     switch(*action) {
2059     case 'e':
2060     case 'E':
2061       if (strcasecmp(CONVRULE_ENGINE_ON_CMD, action) == 0) {
2062         newrule->action |= CONVRULE_ENGINE_ON_BIT;
2063       }
2064       else
2065       if (strcasecmp(CONVRULE_ENGINE_OFF_CMD, action) == 0) {
2066         newrule->action |= CONVRULE_ENGINE_OFF_BIT;
2067       }
2068       break;
2069
2070     case 'C':
2071     case 'c':
2072       if (strcasecmp(CONVRULE_COOKIE_ON_CMD, action) == 0) {
2073         newrule->action |= CONVRULE_COOKIE_ON_BIT;
2074       }
2075       break;
2076     default:
2077       break;
2078     }
2079   }
2080   
2081   pp = prm1;
2082   if (*pp == '!') {
2083     newrule->flags |= CONVRULE_FLAG_NOTMATCH;
2084     pp++;
2085   }
2086
2087   mode = AP_REG_EXTENDED;
2088   if ((regexp = ap_pregcomp((apr_pool_t *)cmd->pool, (const char *)pp, mode)) == NULL)
2089     return "RewriteRule: cannot compile regular expression ";
2090
2091   newrule->regexp = regexp;
2092   if (*prm3)
2093     newrule->encoding = apr_pstrdup(cmd->pool, prm3);
2094   else
2095     newrule->encoding = apr_pstrdup(cmd->pool, "none");
2096
2097   newrule->pc_flag = CONVRULE_PC_FLAG_OFF_BIT;
2098   if (*prm4)
2099     if (strcasecmp(CONVRULE_PC_FLAG_ON_CMD, prm4) == 0)
2100       newrule->pc_flag = CONVRULE_PC_FLAG_ON_BIT;
2101
2102   newrule->user_agent = NULL;
2103   if (*prm5)
2104     newrule->user_agent = apr_pstrdup(cmd->pool, prm5);
2105     
2106   return NULL;
2107 }
2108
2109
2110 static const char *
2111 cmd_set_cookie_dir(
2112   cmd_parms   *cmd, 
2113   void        *mconfig, 
2114   const char  *arg)
2115 {
2116   mod_chxj_config *dconf;
2117
2118
2119   if (strlen(arg) > 4096) 
2120     return "mod_chxj: ChxjCookieDir is too long.";
2121
2122   dconf = (mod_chxj_config *)mconfig;
2123
2124   dconf->cookie_db_dir = apr_pstrdup(cmd->pool, arg);
2125
2126   return NULL;
2127 }
2128
2129
2130 static const char *
2131 cmd_set_cookie_timeout(
2132   cmd_parms   *UNUSED(cmd), 
2133   void        *mconfig, 
2134   const char  *arg)
2135 {
2136   mod_chxj_config *dconf;
2137
2138   if (strlen(arg) > 4096) 
2139     return "mod_chxj: ChxjCookieTimeout is too long.";
2140
2141   if (chxj_chk_numeric(arg) != 0)
2142     return "mod_chxj: ChxjCookieTimeout is not numeric.";
2143
2144   dconf = (mod_chxj_config *)mconfig;
2145
2146   dconf->cookie_timeout = atoi(arg);
2147
2148   return NULL;
2149 }
2150
2151
2152 #if defined(USE_MYSQL_COOKIE)
2153 static const char *
2154 cmd_set_cookie_mysql_database(
2155   cmd_parms   *cmd, 
2156   void        *mconfig, 
2157   const char  *arg)
2158 {
2159   mod_chxj_config  *dconf;
2160
2161   if (strlen(arg) > 255) 
2162     return "mod_chxj: ChxjCookieMysqlDatabase is too long.";
2163
2164   dconf = (mod_chxj_config *)mconfig;
2165
2166   dconf->mysql.database = apr_pstrdup(cmd->pool, arg);
2167
2168   return NULL;
2169 }
2170
2171
2172 static const char *
2173 cmd_set_cookie_mysql_username(
2174   cmd_parms   *cmd, 
2175   void        *mconfig, 
2176   const char  *arg)
2177 {
2178   mod_chxj_config  *dconf;
2179
2180   if (strlen(arg) > 255) 
2181     return "mod_chxj: ChxjCookieMysqlUsername is too long.";
2182
2183   dconf = (mod_chxj_config *)mconfig;
2184
2185   dconf->mysql.username = apr_pstrdup(cmd->pool, arg);
2186
2187   return NULL;
2188 }
2189
2190
2191 static const char *
2192 cmd_set_cookie_mysql_password(
2193   cmd_parms   *cmd, 
2194   void        *mconfig, 
2195   const char  *arg)
2196 {
2197   mod_chxj_config  *dconf;
2198
2199   if (strlen(arg) > 255) 
2200     return "mod_chxj: ChxjCookieMysqlPassword is too long.";
2201
2202   dconf = (mod_chxj_config *)mconfig;
2203
2204   dconf->mysql.password = apr_pstrdup(cmd->pool, arg);
2205
2206   return NULL;
2207 }
2208
2209
2210 static const char *
2211 cmd_set_cookie_mysql_table_name(
2212   cmd_parms   *cmd, 
2213   void        *mconfig, 
2214   const char  *arg)
2215 {
2216   mod_chxj_config  *dconf;
2217
2218   if (strlen(arg) > 255) 
2219     return "mod_chxj: ChxjCookieMysqlTableName is too long.";
2220
2221   dconf = (mod_chxj_config *)mconfig;
2222
2223   dconf->mysql.tablename = apr_pstrdup(cmd->pool, arg);
2224
2225   return NULL;
2226 }
2227
2228 static const char *
2229 cmd_set_cookie_mysql_port(
2230   cmd_parms   *UNUSED(cmd), 
2231   void        *mconfig, 
2232   const char  *arg)
2233 {
2234   mod_chxj_config *dconf;
2235
2236   if (strlen(arg) > 255) 
2237     return "mod_chxj: ChxjCookieMysqlPort is too long.";
2238
2239   dconf = (mod_chxj_config *)mconfig;
2240
2241   if (chxj_chk_numeric(arg) != 0)
2242     return "mod_chxj: ChxjCookieMysqlPort is not numeric.";
2243
2244   dconf = (mod_chxj_config *)mconfig;
2245
2246   dconf->mysql.port = chxj_atoi(arg);
2247
2248   return NULL;
2249 }
2250
2251
2252 static const char *
2253 cmd_set_cookie_mysql_host(
2254   cmd_parms   *cmd, 
2255   void        *mconfig, 
2256   const char  *arg)
2257 {
2258   mod_chxj_config  *dconf;
2259
2260   if (strlen(arg) > 255) 
2261     return "mod_chxj: ChxjCookieMysqlHost is too long.";
2262
2263   dconf = (mod_chxj_config *)mconfig;
2264
2265   dconf->mysql.host = apr_pstrdup(cmd->pool, arg);
2266
2267   return NULL;
2268 }
2269
2270
2271 static const char *
2272 cmd_set_cookie_mysql_socket_path(
2273   cmd_parms   *cmd, 
2274   void        *mconfig, 
2275   const char  *arg)
2276 {
2277   mod_chxj_config  *dconf;
2278
2279   if (strlen(arg) > 4096) 
2280     return "mod_chxj: ChxjCookieMysqlSocketPath is too long.";
2281
2282   dconf = (mod_chxj_config *)mconfig;
2283
2284   dconf->mysql.socket_path = apr_pstrdup(cmd->pool, arg);
2285
2286   return NULL;
2287 }
2288
2289
2290 static const char *
2291 cmd_set_cookie_mysql_charset(
2292   cmd_parms   *cmd, 
2293   void        *mconfig, 
2294   const char  *arg)
2295 {
2296   mod_chxj_config  *dconf;
2297
2298   if (strlen(arg) > 255) 
2299     return "mod_chxj: ChxjCookieMysqlCharset is too long.";
2300
2301   dconf = (mod_chxj_config *)mconfig;
2302
2303   dconf->mysql.charset = apr_pstrdup(cmd->pool, arg);
2304
2305   return NULL;
2306 }
2307 #endif
2308 #if defined(USE_MEMCACHE_COOKIE)
2309 static const char *
2310 cmd_set_cookie_memcache_port(
2311   cmd_parms   *UNUSED(cmd), 
2312   void        *mconfig, 
2313   const char  *arg)
2314 {
2315   mod_chxj_config *dconf;
2316
2317   if (strlen(arg) > 255) 
2318     return "mod_chxj: ChxjCookieMemcachePort is too long.";
2319
2320   dconf = (mod_chxj_config *)mconfig;
2321
2322   if (chxj_chk_numeric(arg) != 0)
2323     return "mod_chxj: ChxjCookieMemcachePort is not numeric.";
2324
2325   dconf = (mod_chxj_config *)mconfig;
2326
2327   dconf->memcache.port = (apr_port_t)chxj_atoi(arg);
2328
2329   return NULL;
2330 }
2331
2332
2333 static const char *
2334 cmd_set_cookie_memcache_host(
2335   cmd_parms   *cmd, 
2336   void        *mconfig, 
2337   const char  *arg)
2338 {
2339   mod_chxj_config  *dconf;
2340
2341   if (strlen(arg) > 255) 
2342     return "mod_chxj: ChxjCookieMemcacheHost is too long.";
2343
2344   dconf = (mod_chxj_config *)mconfig;
2345
2346   dconf->memcache.host = apr_pstrdup(cmd->pool, arg);
2347
2348   return NULL;
2349 }
2350 #endif
2351
2352 static const char *
2353 cmd_set_cookie_lazy_mode(
2354   cmd_parms   *UNUSED(cmd), 
2355   void        *mconfig, 
2356   const char  *arg)
2357 {
2358   mod_chxj_config  *dconf;
2359
2360   if (strlen(arg) > 255) 
2361     return "mod_chxj: ChxjCookieLazyMode is too long.";
2362
2363   dconf = (mod_chxj_config *)mconfig;
2364
2365   if (strcasecmp("TRUE",arg) == 0) {
2366     dconf->cookie_lazy_mode = COOKIE_LAZY_ON;
2367   }
2368   else {
2369     dconf->cookie_lazy_mode = COOKIE_LAZY_OFF;
2370   }
2371
2372   return NULL;
2373 }
2374
2375 static const char *
2376 cmd_set_cookie_store_type(
2377   cmd_parms   *UNUSED(cmd), 
2378   void        *mconfig, 
2379   const char  *arg)
2380 {
2381   mod_chxj_config  *dconf;
2382
2383   if (strlen(arg) > 255) 
2384     return "mod_chxj: ChxjCookieStoreType is too long.";
2385
2386   dconf = (mod_chxj_config *)mconfig;
2387
2388   if (strcasecmp(CHXJ_COOKIE_STORE_TYPE_DBM, arg) == 0) {
2389     dconf->cookie_store_type = COOKIE_STORE_TYPE_DBM;
2390   }
2391   else if (strcasecmp(CHXJ_COOKIE_STORE_TYPE_MYSQL, arg) == 0) {
2392     dconf->cookie_store_type = COOKIE_STORE_TYPE_MYSQL;
2393   }
2394   else if (strcasecmp(CHXJ_COOKIE_STORE_TYPE_MEMCACHE, arg) == 0) {
2395     dconf->cookie_store_type = COOKIE_STORE_TYPE_MEMCACHE;
2396   }
2397   else {
2398     dconf->cookie_store_type = COOKIE_STORE_TYPE_NONE;
2399   }
2400
2401   return NULL;
2402 }
2403
2404 static const char *
2405 cmd_set_forward_url_base(
2406   cmd_parms   *cmd,
2407   void        *mconfig,
2408   const char  *arg)
2409 {
2410  mod_chxj_config *dconf;
2411
2412   if (strlen(arg) > 255)
2413     return "mod_chxj: ChxjForwardUrlBase is too long.";
2414
2415   dconf = (mod_chxj_config *)mconfig;
2416
2417   dconf->forward_url_base = apr_pstrdup(cmd->pool, arg);
2418
2419   return NULL;
2420 }
2421
2422 static const char *
2423 cmd_set_forward_server_ip(
2424   cmd_parms   *cmd,
2425   void        *mconfig,
2426   const char  *arg)
2427 {
2428   mod_chxj_config *dconf;
2429
2430   if (strlen(arg) > 255)
2431     return "mod_chxj: ChxjForwardServerIp is too long.";
2432
2433   dconf = (mod_chxj_config *)mconfig;
2434
2435   dconf->forward_server_ip = apr_pstrdup(cmd->pool, arg);
2436
2437   return NULL;
2438 }
2439
2440 static const char *
2441 cmd_set_new_line_type(
2442   cmd_parms   *UNUSED(cmd), 
2443   void        *mconfig, 
2444   const char  *arg)
2445 {
2446   mod_chxj_config  *dconf;
2447   if (strlen(arg) > 255)
2448     return "mod_chxj: ChxjNewLineType is too long.";
2449
2450   dconf = (mod_chxj_config *)mconfig;
2451
2452   if (strcasecmp(CHXJ_NEW_LINE_TYPE_CRLF, arg) == 0) {
2453     dconf->new_line_type = NLTYPE_CRLF;
2454   }
2455   else if (strcasecmp(CHXJ_NEW_LINE_TYPE_LF, arg) == 0) {
2456     dconf->new_line_type = NLTYPE_LF;
2457   }
2458   else if (strcasecmp(CHXJ_NEW_LINE_TYPE_CR, arg) == 0) {
2459     dconf->new_line_type = NLTYPE_CR;
2460   }
2461   else if (strcasecmp(CHXJ_NEW_LINE_TYPE_NONE, arg) == 0) {
2462     dconf->new_line_type = NLTYPE_NONE;
2463   }
2464   else {
2465     return "mod_chxj: invalid value (ChxjNewLineType)";
2466   }
2467   return NULL;
2468 }
2469
2470
2471 static const command_rec cmds[] = {
2472   AP_INIT_TAKE1(
2473     "ChxjLoadDeviceData",
2474     cmd_load_device_data,
2475     NULL,
2476     OR_ALL,
2477     "Load Device Data"),
2478   AP_INIT_TAKE1(
2479     "ChxjLoadEmojiData",
2480     cmd_load_emoji_data,
2481     NULL,
2482     OR_ALL,
2483     "Load Emoji Data"),
2484   AP_INIT_TAKE1(
2485     "ChxjImageEngine",
2486     cmd_set_image_engine,
2487     NULL,
2488     OR_ALL,
2489     "Convert Target URI"),
2490   AP_INIT_TAKE1(
2491     "ChxjImageCacheDir",
2492     cmd_set_image_cache_dir,
2493     NULL,
2494     OR_ALL,
2495     "Image Cache Directory"),
2496   AP_INIT_TAKE1(
2497     "ChxjImageCacheLimit",
2498     cmd_set_image_cache_limit,
2499     NULL,
2500     OR_ALL,
2501     "Image Cache Limit"),
2502   AP_INIT_TAKE1(
2503     "ChxjImageCopyright",
2504     cmd_set_image_copyright,
2505     NULL,
2506     OR_ALL,
2507     "Copyright Flag"),
2508   AP_INIT_RAW_ARGS(
2509     "ChxjConvertRule",
2510     cmd_convert_rule,
2511     NULL, 
2512     OR_FILEINFO,
2513     "an URL-applied regexp-pattern and a substitution URL"),
2514   AP_INIT_TAKE1(
2515     "ChxjCookieDir",
2516     cmd_set_cookie_dir,
2517     NULL,
2518     OR_ALL,
2519     "save cookie.db directory."),
2520   AP_INIT_TAKE1(
2521     "ChxjCookieTimeout",
2522     cmd_set_cookie_timeout,
2523     NULL,
2524     OR_ALL,
2525     "The compulsion time-out time of the cookie is specified. "),
2526   AP_INIT_TAKE1(
2527     "ChxjCookieStoreType",
2528     cmd_set_cookie_store_type,
2529     NULL,
2530     OR_ALL,
2531     "It specifies preserving of the cookie ahead. (DBM/MYSQL/MEMCACHE)"),
2532   AP_INIT_TAKE1(
2533     "ChxjCookieLazyMode",
2534     cmd_set_cookie_lazy_mode,
2535     NULL,
2536     OR_ALL,
2537     "OneTimeID is negligently done. (TRUE/FALSE)"),
2538 #if defined(USE_MYSQL_COOKIE)
2539   AP_INIT_TAKE1(
2540     "ChxjCookieMysqlHost",
2541     cmd_set_cookie_mysql_host,
2542     NULL,
2543     OR_ALL,
2544     "The MySQL database host used by saving Cookie"),
2545   AP_INIT_TAKE1(
2546     "ChxjCookieMysqlPort",
2547     cmd_set_cookie_mysql_port,
2548     NULL,
2549     OR_ALL,
2550     "The MySQL database port used by saving Cookie"),
2551   AP_INIT_TAKE1(
2552     "ChxjCookieMysqlDatabase",
2553     cmd_set_cookie_mysql_database,
2554     NULL,
2555     OR_ALL,
2556     "The MySQL database name used by saving Cookie"),
2557   AP_INIT_TAKE1(
2558     "ChxjCookieMysqlUsername",
2559     cmd_set_cookie_mysql_username,
2560     NULL,
2561     OR_ALL,
2562     "The MySQL username used by saving Cookie"),
2563   AP_INIT_TAKE1(
2564     "ChxjCookieMysqlPassword",
2565     cmd_set_cookie_mysql_password,
2566     NULL,
2567     OR_ALL,
2568     "The MySQL password used by saving Cookie"),
2569   AP_INIT_TAKE1(
2570     "ChxjCookieMysqlTableName",
2571     cmd_set_cookie_mysql_table_name,
2572     NULL,
2573     OR_ALL,
2574     "The MySQL table name used by saving Cookie"),
2575   AP_INIT_TAKE1(
2576     "ChxjCookieMysqlSocketPath",
2577     cmd_set_cookie_mysql_socket_path,
2578     NULL,
2579     OR_ALL,
2580     "The MySQL socket path used by saving Cookie"),
2581   AP_INIT_TAKE1(
2582     "ChxjCookieMysqlCharset",
2583     cmd_set_cookie_mysql_charset,
2584     NULL,
2585     OR_ALL,
2586     "The MySQL charset used by saving Cookie"),
2587 #endif
2588 #if defined(USE_MEMCACHE_COOKIE)
2589   AP_INIT_TAKE1(
2590     "ChxjCookieMemcacheHost",
2591     cmd_set_cookie_memcache_host,
2592     NULL,
2593     OR_ALL,
2594     "The Memcached host used by saving Cookie"),
2595   AP_INIT_TAKE1(
2596     "ChxjCookieMemcachePort",
2597     cmd_set_cookie_memcache_port,
2598     NULL,
2599     OR_ALL,
2600     "The Memcached port used by saving Cookie"),
2601 #endif
2602   AP_INIT_TAKE1(
2603     "ChxjNewLineType",
2604     cmd_set_new_line_type,
2605     NULL,
2606     OR_ALL,
2607     "HTML new line type (NONE|CRLF|LF|CR). default is CRLF"),
2608   AP_INIT_TAKE1(
2609     "ChxjForwardUrlBase",
2610     cmd_set_forward_url_base,
2611     NULL,
2612     OR_ALL,
2613     "The forward url base(default: {request protocol}://{this server}:{this server port}"),
2614   AP_INIT_TAKE1(
2615     "ChxjForwardServerIp",
2616     cmd_set_forward_server_ip,
2617     NULL,
2618     OR_ALL,
2619     "The forward server ip(default: this server ip)"),
2620   {NULL}
2621 };
2622
2623
2624 /*----------------------------------------------------------------------------*/
2625 /* Dispatch list for API hooks                                                */
2626 /*----------------------------------------------------------------------------*/
2627 module AP_MODULE_DECLARE_DATA chxj_module = {
2628   STANDARD20_MODULE_STUFF, 
2629   chxj_create_per_dir_config,          /* create per-dir    config structures */
2630   chxj_merge_per_dir_config,           /* merge  per-dir    config structures */
2631   chxj_config_server_create,           /* create per-server config structures */
2632   NULL,                                /* merge  per-server config structures */
2633   cmds,                                /* table of config file commands       */
2634   chxj_register_hooks                  /* register hooks                      */
2635 };
2636 /*
2637  * vim:ts=2 et
2638  */