Added preliminary Symbian support.
[silc.git] / lib / silchttp / silchttpphp.c
1 /*
2
3   silchttpphp.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2006 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silc.h"
21 #include "silchttpphp.h"
22
23 /* Executes PHP code and returns result */
24
25 SilcBuffer silc_http_php(char *php_data)
26 {
27   SilcBuffer ret;
28   char *name, tmp[32];
29
30   /* Write the PHP data to temporary file */
31 #ifdef SILC_WIN32
32   name = _mktemp("silchttpphpXXXXXX");
33   if (!name)
34     return NULL;
35 #else
36   memset(tmp, 0, sizeof(tmp));
37   silc_snprintf(tmp, sizeof(tmp) - 1, "/tmp/silchttpphpXXXXXX");
38   if (mkstemp(tmp) == -1)
39     return NULL;
40   name = tmp;
41 #endif /* SILC_WIN32 */
42
43   silc_file_writefile_mode(name, php_data, strlen(php_data), 0600);
44
45   /* Execute PHP */
46   ret = silc_http_php_file(name);
47
48 #ifdef SILC_WIN32
49   _unlink(name);
50 #else
51   unlink(name);
52 #endif /* SILC_WIN32 */
53
54   return ret;
55 }
56
57 /* Loads PHP file and executes the PHP code and returns the result */
58
59 SilcBuffer silc_http_php_file(const char *filename)
60 {
61   SilcBuffer ret = NULL;
62   unsigned char tmp[8192];
63   FILE *fd;
64   int len;
65
66   SILC_LOG_DEBUG(("Executing PHP"));
67
68   memset(tmp, 0, sizeof(tmp));
69   silc_snprintf(tmp, sizeof(tmp) - 1, "php -f %s", filename);
70
71 #ifdef SILC_WIN32
72   fd = _popen(tmp, "r");
73 #else
74   fd = popen(tmp, "r");
75 #endif /* SILC_WIN32 */
76   if (!fd)
77     return NULL;
78
79   /* Read the result */
80   do {
81     len = fread(tmp, 1, sizeof(tmp), fd);
82     if (len < 0) {
83       silc_buffer_free(ret);
84       pclose(fd);
85       return NULL;
86     }
87
88     if (len) {
89       if (!ret) {
90         ret = silc_buffer_alloc(0);
91         if (!ret) {
92           pclose(fd);
93           return NULL;
94         }
95       }
96
97       silc_buffer_format(ret,
98                          SILC_STR_ADVANCE,
99                          SILC_STR_DATA(tmp, len),
100                          SILC_STR_END);
101     }
102   } while (len);
103
104   if (ret) {
105     silc_buffer_format(ret,
106                        SILC_STR_ADVANCE,
107                        SILC_STR_DATA('\0', 1),
108                        SILC_STR_END);
109     silc_buffer_push(ret, silc_buffer_truelen(ret));
110   }
111
112   return ret;
113 }