Apply tizen coding rule
[platform/framework/web/download-provider.git] / provider / download-provider-client-manager.c
1 /*
2  * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <time.h>
21 #include <sys/time.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <fcntl.h>
27 #include <signal.h>
28
29 #include <aul.h>
30 #include <systemd/sd-daemon.h>
31 #include <glib-object.h>
32
33 #include <cynara-client.h>
34 #include <cynara-client-async.h>
35 #include <cynara-creds-socket.h>
36 #include <cynara-creds-dbus.h>
37
38 #include <download-provider.h>
39 #include <download-provider-log.h>
40 #include <download-provider-config.h>
41 #include <download-provider-pthread.h>
42 #include <download-provider-smack.h>
43 #include <download-provider-client.h>
44 #include <download-provider-notification.h>
45 #include <download-provider-notification-manager.h>
46 #include <download-provider-utils.h>
47 #include <download-provider-ipc.h>
48 #include <download-provider-notify.h>
49 #include <download-provider-db-defs.h>
50 #include <download-provider-db.h>
51 #include <download-provider-queue-manager.h>
52 #include <download-provider-client-manager.h>
53 #include <download-provider-plugin-download-agent.h>
54 #include <download-provider-network.h>
55
56 int g_dp_sock = -1;
57 dp_client_slots_fmt *g_dp_client_slots = NULL;
58 static void *g_db_handle = 0;
59 static pthread_mutex_t g_db_mutex = PTHREAD_MUTEX_INITIALIZER;
60 extern pthread_t g_client_manager_tid;
61
62 void dp_terminate(int signo)
63 {
64         TRACE_DEBUG("Received SIGTERM:%d", signo);
65         close(g_dp_sock);
66         g_dp_sock = -1;
67         if (g_client_manager_tid > 0)
68                 pthread_kill(g_client_manager_tid, SIGUSR1);
69 }
70
71 void dp_broadcast_signal()
72 {
73         TRACE_INFO("broadcast");
74         // announce to all thread for clients
75         // signo 10 : ip changed
76         if (g_dp_client_slots != NULL) {
77                 int i = 0;
78                 for (; i < DP_MAX_CLIENTS; i++) {
79                         if (g_dp_client_slots[i].thread > 0 &&
80                                         pthread_kill(g_dp_client_slots[i].thread, 0) != ESRCH)
81                                 pthread_kill(g_dp_client_slots[i].thread, SIGUSR1);
82                 }
83         }
84
85 }
86
87 char *dp_db_get_client_smack_label(const char *pkgname)
88 {
89         char *smack_label = NULL;
90         unsigned length = 0;
91         int errorcode = DP_ERROR_NONE;
92
93         CLIENT_MUTEX_LOCK(&g_db_mutex);
94         if (dp_db_get_client_property_string(g_db_handle, pkgname, DP_DB_COL_SMACK_LABEL, (unsigned char **)&smack_label, &length, &errorcode) < 0)
95                 TRACE_SECURE_ERROR("failed to get smack label for %s", pkgname);
96         CLIENT_MUTEX_UNLOCK(&g_db_mutex);
97
98         return smack_label;
99 }
100
101 static int __dp_db_open_client_manager()
102 {
103         int errorcode = DP_ERROR_NONE;
104         CLIENT_MUTEX_LOCK(&g_db_mutex);
105         if (g_db_handle == 0 || dp_db_check_connection(g_db_handle) < 0) {
106                 if (dp_db_open_client_manager(&g_db_handle, &errorcode) < 0)
107                         TRACE_ERROR("failed to open database errorcode:%d", errorcode);
108         }
109         CLIENT_MUTEX_UNLOCK(&g_db_mutex);
110         return errorcode;
111 }
112
113 static void __dp_db_free_client_manager()
114 {
115         CLIENT_MUTEX_LOCK(&g_db_mutex);
116         if (g_db_handle != 0) {
117                 TRACE_SECURE_DEBUG("TRY to close [%s]", DP_DBFILE_CLIENTS);
118                 dp_db_close(g_db_handle);
119                 g_db_handle = 0;
120         }
121         CLIENT_MUTEX_UNLOCK(&g_db_mutex);
122 }
123
124 static int __dp_accept_socket_new()
125 {
126         int fd_base, listen_fds = sd_listen_fds(1);
127         TRACE_DEBUG("sd_listen_fds:%d", listen_fds);
128
129         if (listen_fds > INT_MAX) {
130                 TRACE_DEBUG("sd_listen_fds:%d", listen_fds);
131                 return -1;
132         }
133
134         for (fd_base = 0 ; fd_base < listen_fds; fd_base++) {
135                 if (sd_is_socket_unix(fd_base + SD_LISTEN_FDS_START, SOCK_STREAM, 1, IPC_SOCKET, 0) >= 0) {
136                         TRACE_INFO("listen systemd socket:%d", fd_base + SD_LISTEN_FDS_START);
137                         return fd_base + SD_LISTEN_FDS_START;
138                 }
139         }
140         return -1;
141 }
142
143 int dp_client_slot_free(dp_client_slots_fmt *slot)
144 {
145         if (slot->client.channel >= 0) {
146                 close(slot->client.channel);
147                 slot->client.channel = -1;
148         }
149         if (slot->client.dbhandle != 0) {
150                 dp_db_close(slot->client.dbhandle);
151                 slot->client.dbhandle = 0;
152         }
153         // free all requests
154         // remove notify fifo
155         if (slot->client.notify >= 0) {
156                 close(slot->client.notify);
157                 slot->client.notify = -1;
158         }
159         dp_notify_deinit(slot->credential.pid);
160         // kill thread
161         if (slot->thread != 0)
162                 pthread_cancel(slot->thread);
163         slot->thread = 0;
164         if (slot->pkgname != NULL) {
165                 TRACE_SECURE_DEBUG("TRY to close [%s]", slot->pkgname);
166                 free(slot->pkgname);
167                 slot->pkgname = NULL;
168         }
169         return 0;
170 }
171
172 // precondition : all slots are empty
173 static int __dp_manage_client_requests(dp_client_slots_fmt *clients)
174 {
175         int errorcode = DP_ERROR_NONE;
176         int i = 0;
177         int slot_index = 0;
178
179         dp_notification_manager_kill();
180         dp_queue_manager_kill();
181
182         // get all clients info from clients database.
183
184         int *ids = (int *)calloc(DP_MAX_CLIENTS, sizeof(int));
185         if (ids == NULL) {
186                 TRACE_ERROR("failed to allocate the clients");
187                 return -1;
188         }
189         // getting ids of clients
190         int rows_count = dp_db_get_ids(g_db_handle, DP_TABLE_CLIENTS, NULL, ids, NULL, DP_MAX_CLIENTS, DP_DB_COL_ACCESS_TIME, "ASC", &errorcode);
191         for (; i < rows_count; i++) {
192                 char *pkgname = NULL;
193                 unsigned length = 0;
194                 errorcode = DP_ERROR_NONE;
195                 if (dp_db_get_property_string(g_db_handle, ids[i], DP_TABLE_CLIENTS, DP_DB_COL_PACKAGE, (unsigned char **)&pkgname, &length, &errorcode) < 0) {
196                         TRACE_ERROR("failed to get pkgname for id:%d", ids[i]);
197                         continue;
198                 }
199
200                 if (pkgname != NULL) {
201                         if (dp_db_remove_database(pkgname, time(NULL), DP_CARE_CLIENT_INFO_PERIOD * 3600) == 0) { // old database
202                                 // remove info from client database;
203                                 if (dp_db_delete(g_db_handle, ids[i], DP_TABLE_CLIENTS, &errorcode) == 0) {
204                                         TRACE_SECURE_ERROR("clear info for %s", pkgname);
205                                         // remove database file
206                                 }
207                                 TRACE_SECURE_INFO("remove database for %s", pkgname);
208                                 free(pkgname);
209                                 continue;
210                         }
211
212                         dp_credential credential;
213                         credential.pid = 0;
214                         if (dp_db_get_property_int(g_db_handle, ids[i], DP_TABLE_CLIENTS, DP_DB_COL_UID, &credential.uid, &errorcode) < 0 ||
215                                         dp_db_get_property_int(g_db_handle, ids[i], DP_TABLE_CLIENTS, DP_DB_COL_GID, &credential.gid, &errorcode) < 0) {
216                                 TRACE_SECURE_ERROR("failed to get credential for %s", pkgname);
217                                 free(pkgname);
218                                 continue;
219                         }
220                         if (dp_mutex_init(&clients[slot_index].mutex, NULL) != 0) {
221                                 TRACE_SECURE_ERROR("failed to initialize mutex for %s", pkgname);
222                                 free(pkgname);
223                                 continue;
224                         }
225                         // open database of a clients
226                         if (dp_db_open_client_v2(&clients[slot_index].client.dbhandle, pkgname) < 0) {
227                                 TRACE_SECURE_ERROR("failed to open database for %s", pkgname);
228                                 // remove this client from clients database
229                                 if (dp_db_delete(g_db_handle, ids[i], DP_TABLE_CLIENTS, &errorcode) == 0) {
230                                         TRACE_SECURE_ERROR("clear info for %s", pkgname);
231                                         // remove database file
232                                         if (dp_db_remove_database(pkgname, time(NULL), 0) == 0)
233                                                 TRACE_SECURE_INFO("remove database for %s", pkgname);
234                                         else
235                                                 TRACE_SECURE_ERROR("failed to remove database for %s", pkgname);
236                                 }
237                                 free(pkgname);
238                                 continue;
239                         }
240
241                         // get ids if state is QUEUED, CONNECTING or DOWNLOADING with auto_download
242                         int *request_ids = (int *)calloc(DP_MAX_REQUEST, sizeof(int));
243                         if (request_ids == NULL) {
244                                 TRACE_SECURE_ERROR("failed to allocate the requests for %s", pkgname);
245                                 free(pkgname);
246                                 continue;
247                         }
248                         int request_count = dp_db_get_crashed_ids(clients[slot_index].client.dbhandle, DP_TABLE_LOGGING, request_ids, DP_MAX_REQUEST, &errorcode);
249                         TRACE_DEBUG("client: %s requests:%d", pkgname, request_count);
250                         int ids_i = 0;
251                         if (request_count > 0) {
252                                 clients[slot_index].pkgname = pkgname;
253                                 clients[slot_index].client.channel = -1;
254                                 clients[slot_index].client.notify = -1;
255                                 clients[slot_index].credential.pid = credential.pid;
256                                 clients[slot_index].credential.uid = credential.uid;
257                                 clients[slot_index].credential.gid = credential.gid;
258                                 for (ids_i = 0; ids_i < request_count; ids_i++) {
259                                         // loading requests from client's database... attach to client.requests
260                                         dp_request_fmt *request = (dp_request_fmt *) calloc(1, sizeof(dp_request_fmt));
261                                         if (request == NULL) {
262                                                 TRACE_ERROR("check memory download-id:%d", request_ids[ids_i]);
263                                                 break;
264                                         }
265                                         request->id = request_ids[ids_i];
266                                         request->agent_id = -1;
267                                         request->state = DP_STATE_QUEUED;
268                                         request->error = DP_ERROR_NONE;
269                                         if (dp_db_get_property_int(clients[slot_index].client.dbhandle, request->id, DP_TABLE_REQUEST, DP_DB_COL_NETWORK_TYPE, &request->network_type, &errorcode) < 0) {
270                                                 TRACE_ERROR("failed to get network type for id:%d", request->id);
271                                                 request->network_type = DP_NETWORK_WIFI;
272                                         }
273                                         request->access_time = (int)time(NULL);
274                                         request->state_cb = 0;
275                                         request->progress_cb = 0;
276                                         if (dp_db_get_property_int(clients[slot_index].client.dbhandle, request->id, DP_TABLE_LOGGING, DP_DB_COL_STARTCOUNT, &request->startcount, &errorcode) < 0) {
277                                                 TRACE_ERROR("failed to get start count for id:%d", request->id);
278                                                 request->startcount = 0;
279                                         }
280                                         request->startcount++;
281                                         request->noti_type = DP_NOTIFICATION_TYPE_NONE;
282                                         if (dp_db_get_property_int(clients[slot_index].client.dbhandle, request->id, DP_TABLE_NOTIFICATION, DP_DB_COL_NOTI_TYPE, &request->noti_type, &errorcode) < 0)
283                                                 TRACE_ERROR("failed to get notification type for id:%d", request->id);
284                                         if (request->noti_type == DP_NOTIFICATION_TYPE_NONE) {
285                                                 TRACE_INFO("enable notification for id:%d", request->id);
286                                                 request->noti_type = DP_NOTIFICATION_TYPE_COMPLETE_ONLY;
287                                         }
288                                         request->progress_lasttime = 0;
289                                         request->received_size = 0; // ?
290                                         request->content_type = DP_CONTENT_UNKNOWN;
291                                         request->file_size = 0; // ?
292                                         if (dp_db_get_property_int(clients[slot_index].client.dbhandle, request->id, DP_TABLE_NOTIFICATION, DP_DB_COL_NOTI_PRIV_ID, &request->noti_priv_id, &errorcode) < 0) {
293                                                 TRACE_ERROR("failed to get notification noti_priv_id for id:%d", request->id);
294                                                 request->noti_priv_id = -1;
295                                         }
296
297                                         dp_request_create(&clients[slot_index].client, request);
298
299                                         if (dp_db_update_logging(clients[slot_index].client.dbhandle, request->id, DP_STATE_QUEUED, DP_ERROR_NONE, &errorcode) < 0) {
300                                                 TRACE_ERROR("update log download-id:%d", request->id);
301                                                 errorcode = DP_ERROR_DISK_BUSY;
302                                                 break;
303                                         }
304                                         if (dp_queue_manager_push_queue((void *)&clients[slot_index], (void *)request) < 0) {
305                                                 errorcode = DP_ERROR_QUEUE_FULL;
306                                                 TRACE_INFO("failed to push to queue for id:%d", request->id);
307                                                 dp_request_destroy(&(clients[slot_index].client), NULL, request);
308                                                 break;
309                                         }
310                                         // notification
311                                         if (dp_notification_manager_push_notification((void *)&clients[slot_index], (void *)request, DP_NOTIFICATION_ONGOING) < 0)
312                                                 TRACE_ERROR("failed to register notification for id:%d", request->id);
313                                 }
314
315                                 slot_index++;
316
317                         } else {
318                                 free(pkgname);
319                         }
320                         free(request_ids);
321                 }
322         }
323         free(ids);
324         TRACE_DEBUG("slot_index:%d", slot_index);
325         if (slot_index > 0)
326                 dp_queue_manager_wake_up();
327         return slot_index;
328 }
329
330 static int __dp_client_run(int clientfd, dp_client_slots_fmt *slot,
331                 dp_credential credential)
332 {
333         int errorcode = DP_ERROR_NONE;
334         // make notify fifo
335         slot->client.notify = dp_notify_init(credential.pid);
336         if (slot->client.notify < 0) {
337                 TRACE_ERROR("failed to open fifo slot:%d", clientfd);
338                 errorcode = DP_ERROR_IO_ERROR;
339         } else {
340                 char *smack_label = NULL;
341                 if (dp_smack_is_mounted() == 1) {
342                         smack_label = dp_smack_get_label_from_socket(clientfd);
343                         if (smack_label == NULL)
344                                 TRACE_SECURE_ERROR("smack_new_label_from_socket");
345                 }
346                 // save client info to database
347                 CLIENT_MUTEX_LOCK(&g_db_mutex);
348                 if (dp_db_update_client_info(g_db_handle,
349                                         slot->pkgname, smack_label,
350                                         credential.uid, credential.gid, &errorcode) < 0) {
351                         TRACE_ERROR("check error:%s", dp_print_errorcode(errorcode));
352                 }
353                 CLIENT_MUTEX_UNLOCK(&g_db_mutex);
354                 free(smack_label);
355         }
356         if (errorcode == DP_ERROR_NONE) {
357
358                 // create a thread for client
359                 if (pthread_create(&slot->thread, NULL,
360                                         dp_client_request_thread, (void *)slot) != 0) {
361                         TRACE_ERROR("failed to create client thread slot:%d", clientfd);
362                         errorcode = DP_ERROR_OUT_OF_MEMORY;
363                         slot->thread = 0;
364                         dp_client_slot_free(slot); // => make pkgname as NULL
365                 } else {
366                         pthread_detach(slot->thread);
367                         TRACE_SECURE_INFO("accept client[%s] pid:%d sock:%d",
368                                         slot->pkgname, credential.pid, clientfd);
369                         slot->client.channel = clientfd;
370                         slot->credential.pid = credential.pid;
371                         slot->credential.uid = credential.uid;
372                         slot->credential.gid = credential.gid;
373                 }
374         }
375         return errorcode;
376 }
377
378
379 static int __dp_client_new(int clientfd, dp_client_slots_fmt *clients,
380                 dp_credential credential)
381 {
382         // search in clients list.
383         // if same pkgname. update it.
384         // search same pkg or pid in clients
385         int errorcode = DP_ERROR_NONE;
386         int i = 0;
387         int pkg_len = 0;
388         char *pkgname = NULL;
389
390         char buffer[256] = { 0, };
391
392         // getting the package name via pid
393         if (aul_app_get_appid_bypid_for_uid(credential.pid, buffer, sizeof(buffer), credential.uid) != AUL_R_OK)
394                 TRACE_ERROR("[CRITICAL] aul_app_get_appid_bypid_for_uid");
395
396         pkgname = strdup(buffer);
397         /*
398         //// TEST CODE ... to allow sample client ( no package name ).
399         if (pkgname == NULL) {
400         //pkgname = dp_strdup("unknown_app");
401         char *temp_pkgname = (char *)calloc(41, sizeof(char));
402         if (temp_pkgname == NULL ||
403         snprintf(temp_pkgname, 41,"unknown_app_%d", credential.pid) < 0) {
404         pkgname = dp_strdup("unknown_app");
405         } else {
406         pkgname = temp_pkgname;
407         }
408         }
409
410         if (pkgname == NULL) {
411         TRACE_ERROR("[CRITICAL] app_manager_get_app_id");
412         return DP_ERROR_INVALID_PARAMETER;
413         }
414         */
415         if ((pkg_len = strlen(pkgname)) <= 0) {
416                 TRACE_ERROR("[CRITICAL] pkgname:%s", pkgname);
417                 free(pkgname);
418                 return DP_ERROR_INVALID_PARAMETER;
419         }
420
421 #ifdef SUPPORT_SECURITY_PRIVILEGE_OLD
422         TRACE_DEBUG("SUPPORT_SECURITY_PRIVILEGE_OLD");
423         int result = security_server_check_privilege_by_sockfd(clientfd, SECURITY_PRIVILEGE_INTERNET, "w");
424         if (result != SECURITY_SERVER_API_SUCCESS) {
425                 TRACE_ERROR("check privilege permission:%d", result);
426                 return DP_ERROR_PERMISSION_DENIED;
427         }
428 #endif
429
430 #if 1
431         TRACE_DEBUG("SUPPORT_SECURITY_PRIVILEGE");
432         // Cynara structure init
433         int ret;
434         cynara *p_cynara = NULL;
435         cynara_configuration *p_conf = NULL;
436         size_t cache_size = 100;
437
438         if (CYNARA_API_SUCCESS != cynara_configuration_create(&p_conf))  { /* error */}
439         if (CYNARA_API_SUCCESS != cynara_configuration_set_cache_size(p_conf, cache_size)) { /* error */ }
440
441         ret = cynara_initialize(&p_cynara, NULL);
442         if (ret != CYNARA_API_SUCCESS) { /* error */ }
443         cynara_configuration_destroy(p_conf);
444
445         // Get client peer credential
446         char *clientSmack;
447         ret = cynara_creds_socket_get_client(clientfd, CLIENT_METHOD_SMACK, &clientSmack);
448         // In case of D-bus peer credential??
449         // ret = cynara_creds_dbus_get_client(DBusConnection *connection, const char *uniqueName,CLIENT_METHOD_SMACK, &clientSmack);
450         if (ret != CYNARA_API_SUCCESS) { /* error */ }
451
452         char *uid;
453         ret = cynara_creds_socket_get_user(clientfd, USER_METHOD_UID, &uid);
454         // In case of D-bus peer credential??
455         // ret = cynara_creds_dbus_get_client(DBusConnection *connection, const char *uniqueName,CLIENT_METHOD_SMACK, &clientSmack);
456         if (ret != CYNARA_API_SUCCESS) { /* error */ }
457
458         /* Concept of session is service-specific.
459          * Might be empty string if service does not have such concept
460          */
461         char *client_session = "";
462
463         // Cynara check
464
465         ret = cynara_check(p_cynara, clientSmack, client_session, uid, "http://tizen.org/privilege/download");
466
467         if (ret == CYNARA_API_ACCESS_ALLOWED) {
468                 TRACE_DEBUG("CYNARA_API_ACCESS_ALLOWED");
469         } else {
470                 TRACE_DEBUG("DP_ERROR_PERMISSION_DENIED");
471                 free(pkgname);
472                 return DP_ERROR_PERMISSION_DENIED;
473         }
474
475         // Cleanup of cynara structure
476         /*
477            if(clientSmack) {
478            free(clientSmack);
479            }
480
481            if(client_session) {
482            free(client_session);
483            }
484
485            if(uid) {
486            free(uid);
487            }
488            */
489         cynara_finish(p_cynara);
490
491 #endif
492
493         // EINVAL: empty slot
494         // EBUSY : occupied slot
495         // locked & thread == 0 : downloading without client <= check target
496         // thread == 0, requests == NULL : clear target
497
498         // Have this client ever been connected before ?
499         for (i = 0; i < DP_MAX_CLIENTS; i++) {
500                 int locked = CLIENT_MUTEX_TRYLOCK(&clients[i].mutex);
501                 if (locked != 0) // empty or used by other thread. it would be same client, but it's busy
502                         continue;
503
504                 TRACE_DEBUG("locked slot:%d", i);
505                 if (locked == 0 && clients[i].thread == 0) { // this slot has run without the client
506                         if (clients[i].pkgname != NULL) {
507                                 // check package name.
508                                 TRACE_DEBUG("check client[%s] slot:%d", clients[i].pkgname, i);
509                                 int cname_len = strlen(clients[i].pkgname);
510                                 if (pkg_len == cname_len &&
511                                                 strncmp(clients[i].pkgname, pkgname, pkg_len) == 0) {
512                                         TRACE_SECURE_INFO("update client[%s] slot:%d pid:%d sock:%d",
513                                                         pkgname, i, credential.pid, clientfd);
514                                         if (clients[i].client.channel >= 0 &&
515                                                         clients[i].client.channel != clientfd) {
516                                                 dp_ipc_socket_free(clients[i].client.channel);
517                                                 if (clients[i].client.notify >= 0)
518                                                         close(clients[i].client.notify);
519                                                 dp_notify_deinit(clients[i].credential.pid);
520                                         }
521                                         errorcode = __dp_client_run(clientfd, &clients[i], credential);
522                                         CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
523                                         if (errorcode != DP_ERROR_NONE)
524                                                 dp_mutex_destroy(&clients[i].mutex);
525                                         free(pkgname);
526                                         return errorcode;
527                                 }
528                         }
529                         if (clients[i].client.requests == NULL) { // clear
530                                 dp_client_slot_free(&clients[i]);
531                                 dp_mutex_destroy(&clients[i].mutex);
532                                 continue;
533                         }
534                 }
535                 CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
536         }
537
538         TRACE_DEBUG("search empty client[%s] slot:%d", pkgname, i);
539         // search empty slot
540         for (i = 0; i < DP_MAX_CLIENTS; i++) {
541                 int locked = CLIENT_MUTEX_TRYLOCK(&clients[i].mutex);
542                 if (locked == EINVAL) {
543                         if (dp_mutex_init(&clients[i].mutex, NULL) == 0) {
544                                 CLIENT_MUTEX_LOCK(&clients[i].mutex);
545                                 TRACE_DEBUG("found empty client[%s] slot:%d", pkgname, i);
546                                 clients[i].pkgname = pkgname;
547                                 clients[i].client.dbhandle = 0;
548                                 clients[i].client.requests = NULL;
549                                 errorcode = __dp_client_run(clientfd, &clients[i], credential);
550                                 CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
551                                 if (errorcode != DP_ERROR_NONE)
552                                         dp_mutex_destroy(&clients[i].mutex);
553                                 return errorcode;
554                         }
555                 }
556                 if (locked == 0)
557                         CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
558         }
559
560         TRACE_SECURE_INFO("busy client[%s] pid:%d sock:%d", pkgname,
561                         credential.pid, clientfd);
562         free(pkgname);
563         return DP_ERROR_TOO_MANY_DOWNLOADS;
564 }
565
566 void *dp_client_manager(void *arg)
567 {
568         fd_set rset, eset, listen_fdset, except_fdset;
569         struct timeval timeout; // for timeout of select
570         socklen_t clientlen;
571         struct sockaddr_un clientaddr;
572         dp_credential credential;
573         unsigned i;
574         int errorcode = DP_ERROR_NONE;
575         GMainLoop *event_loop = (GMainLoop *)arg;
576
577         g_dp_sock = __dp_accept_socket_new();
578         if (g_dp_sock < 0) {
579                 TRACE_ERROR("failed to open listen socket");
580                 g_main_loop_quit(event_loop);
581                 return 0;
582         }
583
584         if (signal(SIGTERM, dp_terminate) == SIG_ERR ||
585                         signal(SIGPIPE, SIG_IGN) == SIG_ERR ||
586                         signal(SIGINT, dp_terminate) == SIG_ERR) {
587                 TRACE_ERROR("failed to register signal callback");
588                 g_main_loop_quit(event_loop);
589                 return 0;
590         }
591
592         dp_notification_clear_ongoings();
593
594 #ifdef PROVIDER_DIR
595         dp_rebuild_dir(PROVIDER_DIR, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
596 #endif
597 #ifdef DATABASE_DIR
598         dp_rebuild_dir(DATABASE_DIR, S_IRWXU);
599 #endif
600 #ifdef DATABASE_CLIENT_DIR
601         dp_rebuild_dir(DATABASE_CLIENT_DIR, S_IRWXU);
602 #endif
603 #ifdef NOTIFY_DIR
604         dp_rebuild_dir(NOTIFY_DIR, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
605 #endif
606
607         dp_client_slots_fmt *clients =
608                 (dp_client_slots_fmt *)calloc(DP_MAX_CLIENTS,
609                                 sizeof(dp_client_slots_fmt));
610         if (clients == NULL) {
611                 TRACE_ERROR("failed to allocate client slots");
612                 g_main_loop_quit(event_loop);
613                 return 0;
614         }
615         g_dp_client_slots = clients;
616         for (i = 0; i < DP_MAX_CLIENTS; i++)
617                 dp_mutex_destroy(&clients[i].mutex); // clear mutex init
618
619         int maxfd = g_dp_sock;
620         FD_ZERO(&listen_fdset);
621         FD_ZERO(&except_fdset);
622         FD_SET(g_dp_sock, &listen_fdset);
623         FD_SET(g_dp_sock, &except_fdset);
624
625         while (g_dp_sock >= 0) {
626
627                 int clientfd = -1;
628
629                 // initialize timeout structure for calling timeout exactly
630                 memset(&timeout, 0x00, sizeof(struct timeval));
631                 timeout.tv_sec = DP_CARE_CLIENT_MANAGER_INTERVAL;
632                 credential.pid = -1;
633                 credential.uid = -1;
634                 credential.gid = -1;
635
636                 rset = listen_fdset;
637                 eset = except_fdset;
638
639                 if (select((maxfd + 1), &rset, 0, &eset, &timeout) < 0) {
640                         TRACE_ERROR("interrupted by terminating");
641                         break;
642                 }
643
644                 if (g_dp_sock < 0) {
645                         TRACE_DEBUG("queue-manager is closed by other thread");
646                         break;
647                 }
648
649                 if (FD_ISSET(g_dp_sock, &eset) > 0) {
650                         TRACE_ERROR("exception of socket");
651                         break;
652                 } else if (FD_ISSET(g_dp_sock, &rset) > 0) {
653
654                         // Anyway accept client.
655                         clientlen = sizeof(clientaddr);
656                         clientfd = accept(g_dp_sock, (struct sockaddr *)&clientaddr,
657                                         &clientlen);
658                         if (clientfd < 0) {
659                                 TRACE_ERROR("too many client ? accept failure");
660                                 // provider need the time of refresh.
661                                 errorcode = DP_ERROR_DISK_BUSY;
662                         }
663
664                         // blocking & timeout to prevent the lockup by client.
665                         struct timeval tv_timeo = {1, 500000}; // 1.5 sec
666                         if (setsockopt(clientfd, SOL_SOCKET, SO_RCVTIMEO, &tv_timeo,
667                                                 sizeof(tv_timeo)) < 0) {
668                                 TRACE_ERROR("failed to set timeout in blocking socket");
669                                 errorcode = DP_ERROR_IO_ERROR;
670                         }
671
672                         dp_ipc_fmt ipc_info;
673                         memset(&ipc_info, 0x00, sizeof(dp_ipc_fmt));
674                         if (read(clientfd, &ipc_info, sizeof(dp_ipc_fmt)) <= 0 ||
675                                         ipc_info.section == DP_SEC_NONE ||
676                                         ipc_info.property != DP_PROP_NONE ||
677                                         ipc_info.id != -1 ||
678                                         ipc_info.size != 0) {
679                                 TRACE_ERROR("peer terminate ? ignore this connection");
680                                 errorcode = DP_ERROR_INVALID_PARAMETER;
681                         }
682
683 #ifdef SO_PEERCRED // getting the info of client
684                         socklen_t cr_len = sizeof(credential);
685                         if (getsockopt(clientfd, SOL_SOCKET, SO_PEERCRED,
686                                                 &credential, &cr_len) < 0) {
687                                 TRACE_ERROR("failed to cred from sock:%d", clientfd);
688                                 errorcode = DP_ERROR_PERMISSION_DENIED;
689                         }
690 #else // In case of not supported SO_PEERCRED
691                         if (read(clientfd, &credential, sizeof(dp_credential)) <= 0) {
692                                 TRACE_ERROR("failed to cred from client:%d", clientfd);
693                                 errorcode = DP_ERROR_PERMISSION_DENIED;
694                         }
695 #endif
696
697                         if (errorcode == DP_ERROR_NONE)
698                                 errorcode = __dp_db_open_client_manager();
699
700                         if (errorcode == DP_ERROR_NONE) {
701                                 if (ipc_info.section == DP_SEC_INIT) {
702
703                                         // new client
704                                         errorcode = __dp_client_new(clientfd, clients, credential);
705
706                                 } else {
707                                         errorcode = DP_ERROR_INVALID_PARAMETER;
708                                 }
709                         }
710                         if (dp_ipc_query(clientfd, -1, ipc_info.section, DP_PROP_NONE, errorcode, 0) < 0)
711                                 TRACE_ERROR("check ipc sock:%d", clientfd);
712
713                         if (errorcode != DP_ERROR_NONE) {
714                                 TRACE_ERROR("sock:%d id:%d section:%s property:%s errorcode:%s size:%d",
715                                                 clientfd, ipc_info.id,
716                                                 dp_print_section(ipc_info.section),
717                                                 dp_print_property(ipc_info.property),
718                                                 dp_print_errorcode(ipc_info.errorcode),
719                                                 ipc_info.size);
720                                 close(clientfd); // ban this client
721                         }
722                         if (errorcode == DP_ERROR_NO_SPACE || errorcode == DP_ERROR_DISK_BUSY) {
723                                 TRACE_ERROR("provider can't work anymore errorcode:%s", dp_print_errorcode(errorcode));
724                                 //break;  // provider will be terminated after sending errorcode by each thread
725                         }
726
727                 } else {
728
729                         // take care zombie client, slots
730                         unsigned connected_clients = 0;
731                         int i = 0;
732                         for (; i < DP_MAX_CLIENTS; i++) {
733
734                                 int locked = CLIENT_MUTEX_TRYLOCK(&clients[i].mutex);
735                                 if (locked == EINVAL) { // not initialized
736                                         continue;
737                                 } else if (locked == EBUSY) { // already locked
738                                         connected_clients++;
739                                         continue;
740                                 }
741
742                                 if (locked == 0) { // locked
743
744                                         // if no client thread, requests should be checked here
745                                         // if no queued, connecting or downloading, close the slot
746                                         if (clients[i].pkgname != NULL) {
747                                                 if (clients[i].thread == 0) {
748                                                         dp_client_clear_requests(&clients[i]);
749                                                         if (clients[i].client.requests == NULL) {
750                                                                 dp_client_slot_free(&clients[i]);
751                                                                 CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
752                                                                 dp_mutex_destroy(&clients[i].mutex);
753                                                                 continue;
754                                                         }
755                                                 }
756                                                 connected_clients++;
757                                         }
758                                         CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
759                                 }
760                         }
761                         TRACE_DEBUG("%d clients are active now", connected_clients);
762                         // terminating download-provider if no clients.
763                         if (connected_clients == 0) {
764                                 if (__dp_manage_client_requests(clients) <= 0) // if no crashed job
765                                         break;
766                         } else {
767                                 dp_queue_manager_wake_up();
768                                 dp_notification_manager_wake_up();
769                         }
770                 }
771
772         }
773         if (g_dp_sock >= 0)
774                 close(g_dp_sock);
775         g_dp_sock = -1;
776
777         dp_queue_manager_kill();
778         dp_notification_clear_ongoings();
779         dp_notification_manager_kill();
780
781         __dp_db_free_client_manager();
782
783         // kill other clients
784         TRACE_DEBUG("try to deallocate the resources for all clients");
785         for (i = 0; i < DP_MAX_CLIENTS; i++) {
786                 int locked = CLIENT_MUTEX_TRYLOCK(&clients[i].mutex);
787                 if (locked == EBUSY) { // already locked
788                         CLIENT_MUTEX_LOCK(&clients[i].mutex);
789                 } else if (locked == EINVAL) { // not initialized, empty slot
790                         continue;
791                 }
792                 dp_client_slot_free(&clients[i]);
793                 CLIENT_MUTEX_UNLOCK(&clients[i].mutex);
794                 dp_mutex_destroy(&clients[i].mutex);
795         }
796         free(clients);
797         // free all resources
798
799         TRACE_INFO("client-manager's working is done");
800         g_main_loop_quit(event_loop);
801         return 0;
802 }