blob: 1039115cf054e3509109c840091e7d9fc1e17036 [file] [log] [blame]
Wayne Davison0f78b812006-04-25 20:23:34 +00001/*
2 * Support the max connections option.
3 *
4 * Copyright (C) 1998 Andrew Tridgell
Wayne Davisonc5fabfb2020-04-09 15:11:37 -07005 * Copyright (C) 2006-2020 Wayne Davison
Wayne Davison0f78b812006-04-25 20:23:34 +00006 *
7 * This program is free software; you can redistribute it and/or modify
Wayne Davison8e41b682007-07-10 13:55:49 +00008 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
Wayne Davison0f78b812006-04-25 20:23:34 +000011 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
Wayne Davisone7c67062006-04-25 23:51:12 +000017 * You should have received a copy of the GNU General Public License along
Wayne Davison4fd842f2007-07-07 05:33:14 +000018 * with this program; if not, visit the http://fsf.org website.
Wayne Davison0f78b812006-04-25 20:23:34 +000019 */
Andrew Tridgell0c515f11998-05-13 08:52:12 +000020
Andrew Tridgell0c515f11998-05-13 08:52:12 +000021#include "rsync.h"
22
Wayne Davison21cafc52007-09-18 14:09:38 +000023/* A simple routine to do connection counting. This returns 1 on success
24 * and 0 on failure, with errno also being set if the open() failed (errno
25 * will be 0 if the lock request failed). */
26int claim_connection(char *fname, int max_connections)
Andrew Tridgell0c515f11998-05-13 08:52:12 +000027{
28 int fd, i;
Andrew Tridgell0c515f11998-05-13 08:52:12 +000029
Wayne Davisond34cd632007-09-18 14:14:22 +000030 if (max_connections == 0)
Wayne Davison236df012007-09-18 14:11:25 +000031 return 1;
Andrew Tridgell8d72ef61998-07-17 05:37:18 +000032
Wayne Davison236df012007-09-18 14:11:25 +000033 if ((fd = open(fname, O_RDWR|O_CREAT, 0600)) < 0)
34 return 0;
Andrew Tridgell0c515f11998-05-13 08:52:12 +000035
Wayne Davison236df012007-09-18 14:11:25 +000036 /* Find a free spot. */
37 for (i = 0; i < max_connections; i++) {
38 if (lock_range(fd, i*4, 4))
39 return 1;
Andrew Tridgell0c515f11998-05-13 08:52:12 +000040 }
41
Wayne Davison236df012007-09-18 14:11:25 +000042 close(fd);
43
Wayne Davison21cafc52007-09-18 14:09:38 +000044 /* A lock failure needs to return an errno of 0. */
Andrew Tridgell8d72ef61998-07-17 05:37:18 +000045 errno = 0;
Andrew Tridgell31593dd1998-05-13 09:38:54 +000046 return 0;
Andrew Tridgell0c515f11998-05-13 08:52:12 +000047}